0

I have pairs like these: (-102,-56), (123, -56). First value from the pairs represents the lower 8 bits and the second value represents the upper 8 bits, both are in signed decimal form. I need to convert these pairs into a single 16 bit values.

I think I was able to convert (-102,-56) pair by:

l = bin(-102 & 0b1111111111111111)[-8:]
u = bin(-56 & 0b1111111111111111)[-8:]
int(u+l,2)

But when I try to do the same with (123, -56) pair I get the following error:

ValueError: invalid literal for int() with base 2: '11001000b1111011'.

I understand that it's due to the different lengths for different values and I need to fill them up to 8 bits.

Am I approaching this completely wrong? What's the best way to do this so it works both on negative and positive values?

UPDATE: I was able to solve this by:

low_int = 123
up_int = -56
(low_int & 0xFF) | ((up_int & 0xFF) << 8)
Gvantsa
  • 69
  • 6

3 Answers3

0

You can try to shift the first value 8 bits: try to use the logic described here https://stackoverflow.com/a/1857965/8947333

Be Chiller Too
  • 2,502
  • 2
  • 16
  • 42
0

Just guessing

l, u = -102 & 255, -56 & 255
# shift 8 bits to left
u << 8 + l
Alexander Volkovsky
  • 2,588
  • 7
  • 13
0

Bitwise operations are fine, but not strictly required.

In the most common 2's complement representation for 8 bits:

-1 signed == 255 unsigned
-2 signed == 254 unsigned
...
-127 signed = 129 usigned
-128 signed = 128 usigned

simply the two absolute values always give the sum 256.

Use this to convert negative values:

if b < 0:
    b += 256

and then combine the high and low byte:

value = 256 * hi8 + lo8
VPfB
  • 14,927
  • 6
  • 41
  • 75