2

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...

Meteorite
  • 344
  • 1
  • 5
  • 17
  • 1
    What do you mean by "8 binaries"? What is the type of the data? There is no builtin type in Python for a single byte. What do you want to do with that byte once you have it? – BrenBarn Sep 27 '14 at 20:50
  • @BrenBarn The 8 binaries are integers. I want to write this byte I get to a binary file. – Meteorite Sep 27 '14 at 20:52
  • In your example, you seem to have a string containing 8 characters, not an integer. If you want to write the byte to a binary file, you can do that just as well with a byte array of length 1. – BrenBarn Sep 27 '14 at 20:53

2 Answers2

2

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'

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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.

Community
  • 1
  • 1
aneroid
  • 12,983
  • 3
  • 36
  • 66