DEV Community

221910304057VIVEK
221910304057VIVEK

Posted on

How to convert string to binary in python

Strings are an array of Unicode code characters.

Binary is a base-2 number system consisting of 0's and 1's. The computer understands binary. The computer sees the string in binary format i.e 'H'=1001000.

The string as seen by the computer is a binary number which is an ASCCI value( Decimal number) of the string converted to binary.

String to binary

To convert a string to binary we first append( join ) the string's individual ASCII values to a list l by using the function ord(_string).

The function ord(_string) gives the ASCII value of the string. i.e ord(H) = 72 , ord(e) = 101.

Then from the list of ASCII values we convert them to binary by using the function bin(_integer).

The function bin(_integer) converts decimal number to a binary number.
i.e bin(72) = 1001000

Then append(add) these binary values to a list m. Then the list m now consists of the binary numbers from the strings given and can be returned or printed.


import math

def toBinary(a):
  l,m=[],[]
  for i in a:
    l.append(ord(i))
  for i in l:
    m.append(int(bin(i)[2:]))
  return m

print("''Hello world'' in binary is ") 
print(toBinary("Hello world"))

Enter fullscreen mode Exit fullscreen mode

Top comments (0)