Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ASCII to binary

Is there a builtin function that converts ASCII to binary?

For example. converts 'P' to 01010000.

I'm using Python 2.6.6

like image 837
Favolas Avatar asked Dec 24 '10 00:12

Favolas


People also ask

How do you convert char to binary in Python?

Method #1 : Using join() + ord() + format() The combination of above functions can be used to perform this particular task. The ord function converts the character to it's ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string.

How do you convert data to binary in Python?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

How do you convert ASCII to value in Python?

chr () is a built-in function in Python that is used to convert the ASCII code into its corresponding character. The parameter passed in the function is a numeric, integer type value. The function returns a character for which the parameter is the ASCII code.


2 Answers

How about two together?

bin(ord('P'))
# 0b1010000
like image 130
Steve Tjoa Avatar answered Oct 09 '22 23:10

Steve Tjoa


Do you want to convert bytes or characters? There's a difference.

If you want bytes, then you can use

# Python 2.x
' '.join(bin(ord(x))[2:].zfill(8) for x in u'שלום, עולם!'.encode('UTF-8'))

# Python 3.x
' '.join(bin(x)[2:].zfill(8) for x in 'שלום, עולם!'.encode('UTF-8'))

The bin function converts an integer to binary. The [2:] strips the leading 0b. The .zfill(8) pads each byte to 8 bits.

like image 32
dan04 Avatar answered Oct 09 '22 23:10

dan04