简体   繁体   English

在Python中将二进制表示形式转换为带符号的64位整数

[英]Converting binary representation to signed 64 bit integer in Python

Against the advice of online resources, I'm using Python to do some simple bit shifting in one of my scripts. 反对在线资源的建议,我使用Python在我的一个脚本中进行了一些简单的移位。 The bit shifting is fine, it's representing the result that's difficult. 移位很好,它表示难以获得的结果。 Let me explain. 让我解释。

I have a 64 bit binary representation 我有一个64位二进制表示

1000010101010111010101010101010101010101010101010111010101010101

which, when represented as a signed integer, should be negative. 当以有符号整数表示时,它应该为负数。 However, Python defaults to type long , preventing the number from being signed by the first bit, yielding the number 9608242155010487637 . 但是,Python默认类型为long ,以防止数字被第一位签名,从而产生数字9608242155010487637

How can I get Python to recognize the sign bit in 64 bits? 如何让Python识别64位的符号位?

To clarify, I'm using Python 2.7. 为了澄清,我正在使用Python 2.7。

You can use struct , like this: 您可以使用struct ,如下所示:

>>> import struct
>>> struct.unpack('l',struct.pack('P',
int('1000010101010111010101010101010101010101010101010111010101010101',
2)))
#=> (-8838501918699063979,)

The result is a tuple, which you can then request the first element of: 结果是一个元组,然后您可以请求以下内容的第一个元素:

>>> struct.unpack('l',struct.pack('P',
int('1000010101010111010101010101010101010101010101010111010101010101',
2)))[0]
#=> -8838501918699063979

Try the bitstring module: 尝试使用bitstring模块:

>>> from bitstring import BitArray
>>> s = '1000010101010111010101010101010101010101010101010111010101010101'
>>> BitArray(bin=s).int
-8838501918699063979

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

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