Is there a builtin function that converts ASCII to binary?
For example. converts 'P' to 01010000.
I'm using Python 2.6.6
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
asked Dec 24, 2010 at 0:46
Favolas
7,28130 gold badges81 silver badges133 bronze badges
3 Answers 3
How about two together?
bin(ord('P'))
# 0b1010000
answered Dec 24, 2010 at 0:49
Steve Tjoa
61.5k18 gold badges93 silver badges103 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Cripto
What does the 0b mean at the start of it
Devon M
@Steve that is actually unusable binary, its only 7 characters, "P" is 01010000 but that code is removing the leading 0, outputting only 1010000 which is only 7 characters and therefore unusable
Geremia
@Cripto
0b means the number is expressed in binary (base 2). 0x would mean hexadecimal (base 16).Geremia
@DevonM Leading zeros don't matter.
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.
answered Dec 24, 2010 at 1:11
dan04
92.1k23 gold badges169 silver badges206 bronze badges
Comments
bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in "Hello world"), 0))
this is for multiple characters
j0k
22.8k28 gold badges81 silver badges90 bronze badges
answered Dec 24, 2010 at 0:51
Saif al Harthi
2,9641 gold badge24 silver badges26 bronze badges
Comments
lang-py