3

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

1

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Binary shift operator:

(second_byte << 8) + first_byte

Same as:

second_byte * 256 + first_byte

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.