简体   繁体   English

将 hexstr 转换为带符号的 integer - Python

[英]Converting hexstr to signed integer - Python

I have this hexstr 0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877 , in decimal terms it should give -580140491462537 .我有这个 hexstr 0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877 ,以十进制表示它应该给出-580140491462537 However doing the below leads to bad answers.但是,执行以下操作会导致错误的答案。 Can someone help?有人可以帮忙吗?

In: test = '0xfffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877'
In: int(test,16)
Out: 11579208923731619542357098500868790785326998466564056403945758342777263817739

First convert the string to bytes.首先将字符串转换为字节。 You'll have to remove the leading "0x".您必须删除前导“0x”。 Then use int.from_bytes and specify that it's signed and big-endian.然后使用 int.from_bytes 并指定它是有符号的和大端的。

In: int.from_bytes(bytes.fromhex(test[2:]), byteorder="big", signed=True)
Out: -580140491462537

I've adapted this answer我已经改编了这个答案

# hex string to signed integer
def htosi(val):
    uintval = int(val, 16)
    bits = 4 * len(val)
    indicative_binary = 2 ** (bits)
    indicative_binary_1 = 2 ** (bits-1)
    if uintval >= indicative_binary_1:
        uintval = int(0 - (indicative_binary - uintval))
    return uintval

This does require a pure hex string:这确实需要一个纯十六进制字符串:

test1 = 'fffffffffffffffffffffffffffffffffffffffffffffffffffdf05d84162877'
print(htosi(test1))

-580140491462537

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

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