JakobVinkas
JakobVinkas

Reputation: 1063

Combining two bytes in Python

I have a problem where I get two bytes represented as an int from 0-255, two bytes are supposed to represent one value. Right now I am doing it like this, but it takes way to a long time. Any tips?

bin_string = '0b' + bin(int(second_byte))[2:].zfill(8) + bin(int(first_byte))[2:].zfill(8)
result = float(literal_eval(bin_string))

example: 
203 -> 11001011
101 -> 01100101
-> 1100101101100101 -> 52069

I feel like there could be a simple mathematical formula but I cannot seem to figure it out ...

Upvotes: 3

Views: 3232

Answers (3)

Alfe
Alfe

Reputation: 59436

If you get your bytes in a bytes value, i. e. a string of bytes, or if you want to put your bytes into one, then you should have a look at the struct module:

 struct.unpack('h', b'\x00\x01')

will return (256,) which is a tuple of all the unpacked stuff from the string b'\x00\x01' according to the format 'h'.

Upvotes: 0

GBrandt
GBrandt

Reputation: 685

Binary shift operator:

(second_byte << 8) + first_byte

Same as:

second_byte * 256 + first_byte

Upvotes: 0

meowgoesthedog
meowgoesthedog

Reputation: 15035

Left-shift the second byte by 8 bits and bitwise OR it with the first byte:

(second_byte << 8) | first_byte

For extra safety clamp both bytes to [0, 255] with a bitwise AND:

((second_byte & 0xFF) << 8) | (first_byte & 0xFF)

Upvotes: 5

Related Questions