我有一个十六进制字符串f6befc34e3de2d30。我想把它转换成长签,但是
x['id'], = struct.unpack('>q', 'f6befc34e3de2d30'.decode('hex'))给予:
-0b100101000001000000111100101100011100001000011101001011010000
0b1111011010111110111111000011010011100011110111100010110100110000期望的。
谢谢!
发布于 2017-12-19 10:50:28
你可以做long('f6befc34e3de2d30', 16)
bin(long('f6befc34e3de2d30', 16))
>>> '0b1111011010111110111111000011010011100011110111100010110100110000'编辑:跟进@Panzer的评论。对于基于ALU硬件的C类型long实现来说,情况就是如此。您不可能有大于2^63的带符号整数。然而,Python的实现是不同的,它依赖于大数的数组表示和Karatsuba算法的算术运算。这就是为什么这个方法有效。
编辑2:后续操作问题。不存在“第一位为符号”的问题。在您的问题中,您明确地希望使用Python的long构造,在某种意义上,它使用的表示与C中可能熟悉的表示不同,因此实现并不是您所期望的那样。相反,它将大整数表示为数组。所以,如果你想要实现某种第一位逻辑,你必须自己去做。我在这方面没有任何文化或经验,所以以下这些可能是完全错误的,因为有人知道他的东西,但还是让我给你我的看法。
我看到了两种前进的方式。在第一个协议中,您同意使用最大长度的约定,然后实现ALU所做的相同类型的逻辑。让我们说,为了论证起见,我们希望在范围[-2^127, 2^127-1]中使用符号long。我们可以做以下工作
MAX_LONG = long('1' + "".join([str(0)]*127), 2)
def parse_nb(s):
# returns the first bit and the significand in the case of a usual
# integer representation
b = bin(long(s, 16))
if len(b) < 130: # deal with the case where the leading zeros are absent
return "0", b[2:]
else:
return b[2], b[3:]
def read_long(s):
# takes an hexadecimal representation of a string, and return
# the corresponding long with the convention stated above
sign, mant = parse_nb(s)
b = "0b" + mant
if sign == "0":
return long(b, 2)
else:
return -MAX_LONG + long(b, 2)
read_long('5')
>>> 5L
# fffffffffffffffffffffffffffffffb is the representation of -5 using the
# usual integer representation, extended to 128 bits integers
read_long("fffffffffffffffffffffffffffffffb")
>>> -5L对于第二种方法,您不认为存在MAX_LONG,而是认为第一个位始终是符号位。然后,您必须修改上面的parse_nb方法。我将此作为一项练习:)。
https://stackoverflow.com/questions/47885067
复制相似问题