Converting an integer to double-byte hex using Python

I need to take an integer (e.g. -200) and change it to hexadecimal (FF 38) and then to an integer 0-255 to send via the serial port. An example of this was:

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

I tried to use struct.pack('>h', -200), but returned an invalid value. I also tried hex(), but this is also a negative hex value.

I do not know what else I should try.

+4
source share
2 answers
>>> hex(struct.unpack('>H', struct.pack('>h', -200))[0])
'0xff38'

-200 2- int. unsigned 2- int. 65336, hex ff38


0-255, :

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


Requisite struct

+3

:

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

, , (.. ), , hex, .

0

Source: https://habr.com/ru/post/1530357/


All Articles