且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两个在Python中的十六进制数补

更新时间:2023-11-08 21:18:04

您得知道你的数据的至少宽度。例如,0xc158a854有8个十六进制数字,因此一定要宽至少32位;这似乎是一个无符号的32位值。我们可以使用一些位操作进行处理:

You'll have to know at least the width of your data. For instance, 0xc158a854 has 8 hexadecimal digits so it must be at least 32 bits wide; it appears to be an unsigned 32 bit value. We can process it using some bitwise operations:

In [232]: b = 0xc158a854

In [233]: if b >= 1<<31: b -= 1<<32

In [234]: b
Out[234]: -1051154348L

第l这里标志着Python 2中已切换到加工值作为长;它通常并不重要,但是在这个案例表明,我一直在与通用INT范围此安装以外的值。该工具从二元结构的数据,如UDP数据包是 struct.unpack ;如果你只是告诉它你的价值是摆在首位签约时,会产生正确的值:

The L here marks that Python 2 has switched to processing the value as a long; it's usually not important, but in this case indicates that I've been working with values outside the common int range for this installation. The tool to extract data from binary structures such as UDP packets is struct.unpack; if you just tell it that your value is signed in the first place, it will produce the correct value:

In [240]: s = '\xc1\x58\xa8\x54'

In [241]: import struct

In [242]: struct.unpack('>i', s)
Out[242]: (-1051154348,)

这是假设补重presentation;一的补(例如在UDP中使用的校验和),符号和幅度,或IEEE 754浮点是数字一些不常见的编码。

That assumes two's complement representation; one's complement (such as the checksum used in UDP), sign and magnitude, or IEEE 754 floating point are some less common encodings for numbers.