简体   繁体   English

使用Python将整数转换为双字节十六进制

[英]Translating an integer into two-byte hexadecimal with Python

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. 我需要取一个整数(例如,-200)并将其更改为十六进制(FF 38),然后转换为整数0-255以通过串行发送。 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. 我尝试过使用struct.pack('>h', -200)但返回的值不正确。 I also tried hex() but that returned a negative hex value that was incorrect as well. 我也尝试了hex()但是返回了一个负十六进制值也是不正确的。

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 . 首先,将-200打包为带符号的2字节short int Then you unpack that data as an unsigned 2-byte short int . 然后将该数据解压缩为无符号的2字节short int This gives you 65336, of which hex is ff38 这给你65336,其中hexff38


If you need to send 0-255 integers, this might work better: 如果你需要发送0-255整数,这可能会更好:

>>> 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 关于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. 请注意,您必须注意正确处理非负数(即不要使用二进制补码)以及当hex返回的字符串长度变化时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM