4

I need to take an integer (for example, -200) and change it into a hexadecimal (FF 38), then into an integer 0-255 to send via serial. The example I was given was:

-200 = hex FF38 = [hex FF] [hex 38] = [255] [56]

I've tried using struct.pack('>h', -200) but that returned the incorrect value. I also tried hex() but that returned a negative hex value that was incorrect as well.

I don't know what else I should be trying.

1
  • Do you need to send a decimal integer b'255' (three bytes) or just a as a byte: b'\xff' (single byte)? Commented Mar 6, 2014 at 22:40

2 Answers 2

3
>>> hex(struct.unpack('>H', struct.pack('>h', -200))[0])
'0xff38'

First, you pack the -200 as a signed 2-byte short int. Then you unpack that data as an unsigned 2-byte short int. This gives you 65336, of which hex is ff38


If you need to send 0-255 integers, this might work better:

>>> struct.unpack('>BB', struct.pack('>h', -200))
(255, 56)
>>> struct.unpack('>BB', struct.pack('>h', 200))
(0, 200)

Where you're unpacking into two unsigned chars


Requisite documentation on struct

Sign up to request clarification or add additional context in comments.

5 Comments

This works great for positive numbers, but what about negative numbers? I tried 200 and -200 and got the same thing.
You shouldn't have... I've edited my answer with an example of each
Had the packing been unsigned, it would have raised an exception: struct.error: integer out of range for 'H' format code
+1. To be clear: struct.pack('>h', n) converts an integer assert n.bit_length() <= 16 into two-byte sequence: '\xff\x38'. No other calls are necessary unless OP wants a decimal representation for some reason then map(str, bytearray(b'\xff\x38')) == ['255', '56']
Yes, I used the below method and it worked perfectly, thank you!
0

Two's complement arithmetic and some string slicing:

hex(200 - (1 << 16)) #2 bytes -> 16 bits
Out[26]: '-0xff38'

int(hex(200 - (1 << 16))[-4:-2], 16)
Out[28]: 255

int(hex(200 - (1 << 16))[-2:], 16)
Out[29]: 56

Note that you'll have to take care to correctly handle non-negative numbers (i.e. don't take the two's complement) and when the length of the string returned by hex is of varying length.

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.