Meteorite
Meteorite

Reputation: 374

How to convert a 8-bit number to an actual byte in Python?

Say I have 8 bits

01010101

which equals the byte

u

But I what I actually have is 8 binaries(well, integers). How do I convert these 8 binaries to the corresponding byte?

I'm trying

byte = int(int('01010101'), 2)
byte = chr(byte)
byte = bytes(byte)

But this gives me a bytes array instead of a single byte...

Upvotes: 2

Views: 6227

Answers (2)

aneroid
aneroid

Reputation: 15962

What version of python are you on? I get the 85 and 'U' using the same statements as you did, using 2.7.8:

int('01010101', 2)
>>> 85
int(int('01010101', 2))  # not needed
>>> 85
chr(int('01010101', 2))
>>> 'U'
bytes(chr(int('01010101', 2)))  # not needed
>>> 'U'

To actually write the binary data to file, see this answer (for py 2 and 3) and this. File mode should be 'wb'. And don't convert to chr.

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117866

The following is interpreted as an octal, since it is prefixed with '0'

01010101

If you want to interpret this as binary, you add the prefix '0b'

>>> 0b01010101
85

This is the same as representing the number as int

>>> int(0b01010101)
85

And to represent the value as chr

>>> chr(0b01010101)
'U'

Also note the prefix for hex is '0x'

Upvotes: 2

Related Questions