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.
>>> 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
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 (ie don't take the two's complement) and when the length of the string returned by hex
is of varying length.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.