Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to convert string to binary in Python

Vivek Tangirala

Strings are an array of Unicode code characters.

Binary is a base-2 number system consisting of 0’s and 1’s that computers understand. The computer sees strings in binary format, i.e., ‘H’=1001000.

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

String to binary

To convert a string to binary, we first appendjoin the string’s individual ASCII values to a list (l) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer). Next, we can append these binary values to a list (m) so that 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"))

Binary to string

In order to pass a list of binary numbers to the function, we first convert the individual numbers to ASCII value by binary to decimal (i.e., 1001000 = 72 , 1100101 = 101).

72 and 101 are ASCII values.

k=int(math.log10(i))+1 gives number of digits in a given number i. These ASCII values are then appendedadded to the list l, and the list of ASCII values is converted to a string with the chr(number) function (i.e., chr(72)=H , chr(101)=e).

Finally, the string is appendedadded to an empty string (m) and is returned.

These functions can be now used to convert string to binary and vice-versa.

import math

def toString(a):
  l=[]
  m=""
  for i in a:
    b=0
    c=0
    k=int(math.log10(i))+1
    for j in range(k):
      b=((i%10)*(2**j))   
      i=i//10
      c=c+b
    l.append(c)
  for x in l:
    m=m+chr(x)
  return m

print(" \n ''[1001000, 1100101, 1101100, 1101100, 1101111,]'' in string is ")
print(toString([1001000, 1100101, 1101100, 1101100, 1101111,]))

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring