两个在Python中的十六进制数补 [英] Two's complement of Hex number in Python

查看:1155
本文介绍了两个在Python中的十六进制数补的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面a和b(十六进制),重presenting补符号二进制数。
例如:

Below a and b (hex), representing two's complement signed binary numbers. For example:

a = 0x17c7cc6e
b = 0xc158a854

现在我想知道的签署再次presentation急症室; b在基地10 的对不起,我水平低程序员,新的Python。觉得问这个非常愚蠢的。我不关心其他库的,但答案应该是简单和直接的。背景:A和b被从UDP分组中提取的数据。我有过的格式无法控制。所以,请不要给我将承担前手我可以改变这些可变因素的格式回答。

Now I want to know the signed representation of a & b in base 10. Sorry I'm a low level programmer and new to python; feel very stupid for asking this. I don't care about additional library's but the answer should be simple and straight forward. Background: a & b are extracted data from a UDP packet. I have no control over the format. So please don't give me an answer that would assume I can change the format of those varibles before hand.

我已经转换A和b代入这个以下内容:

I have converted a & b into the following with this:

aBinary = bin(int(a, 16))[2:].zfill(32) => 00010111110001111100110001101110 => 398969966
bBinary = bin(int(b, 16))[2:].zfill(32) => 11000001010110001010100001010100 => -1051154348

我试图做这样的事情(不工作):

I was trying to do something like this (doesn't work):

if aBinary[1:2] == 1:
aBinary = ~aBinary + int(1, 2)

什么是蟒蛇?这样做的正确方法

推荐答案

您得知道你的数据的至少宽度。例如,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.

这篇关于两个在Python中的十六进制数补的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆