DEV Community

221910304057VIVEK
221910304057VIVEK

Posted on

2 2

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay