10

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,048,767
  • 296
  • 4,058
  • 3,343
Favolas
  • 6,963
  • 29
  • 75
  • 127

3 Answers3

17

How about two together?

bin(ord('P'))
# 0b1010000
Steve Tjoa
  • 59,122
  • 18
  • 90
  • 101
  • 1
    What does the 0b mean at the start of it – Cripto Jun 27 '13 at 01:40
  • @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 – Devon M Feb 04 '14 at 19:24
8

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.

dan04
  • 87,747
  • 23
  • 163
  • 198
0
bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in "Hello world"), 0))

this is for multiple characters

j0k
  • 22,600
  • 28
  • 79
  • 90
Saif al Harthi
  • 2,948
  • 1
  • 21
  • 26