Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
特定字节大小的整数的Python二进制值_Python_Python 3.x_Binary_Bit Manipulation - Fatal编程技术网

特定字节大小的整数的Python二进制值

特定字节大小的整数的Python二进制值,python,python-3.x,binary,bit-manipulation,Python,Python 3.x,Binary,Bit Manipulation,我知道python可能不是最好的工具,但假设我有一个值,我想显示为无符号字符,其值介于-128和127之间。例如: # ok for positive number >>> f'0b{1:>08b}' '0b00000001' # how to do it for negative number? >>> f'0b{-1:>08b}' # should be 0b11111111 '0b000000-1' # how to do it for

我知道python可能不是最好的工具,但假设我有一个值,我想显示为
无符号字符
,其值介于
-128
127
之间。例如:

# ok for positive number
>>> f'0b{1:>08b}' 
'0b00000001'

# how to do it for negative number?
>>> f'0b{-1:>08b}' # should be 0b11111111
'0b000000-1'

# how to do it for 2's complement?
>>> f'0b{~1:>08b}' # should be 0b11111110
'0b00000-10'
如何在python中显示此内容?

使用模256

# positive number is the same
>>> f'0b{1 % 0x100:>08b}' 
'0b00000001'

# correct bit pattern, were you to notate -1 in a signed int8
# same as notating 255 in unsigned int8, which is what -1 % 255 is
>>> f'0b{-1 % 0x100:>08b}'
'0b11111111'

# flipped bits from 1, truncated to only the least significant 8 digits
>>> f'0b{~1 % 0x100:>08b}'
'0b11111110'

本质上,这只是“将有符号字符转换为无符号字符,并打印位模式”——使用模运算符的好处是总是得到一个正数,如果模是2的幂,小于该模数的每一位的位模式都保持完全相同。

您可以尝试手动设置这样的位,知道
2^n-1
设置第一个
n
位:

>>> negative   =lambda value, bits: bin(2**bits-1-value+1)
>>> complement =lambda value, bits: bin(2**bits-1-value)

# to verify (note, python doesn't 'know' its 1 byte so will
# equal 256 unless we do the 1-byte mask with &0xFF
>>> (1+int(complement(1,8),2))&0xFF
0

@juanpa.arrivillaga好的,这就像是
pack
——基本上我只是想用python解释器快速计算c中的值(如果可能的话),谢谢这太酷了。老实说,这是我第一次看到用“负数”的模运算。而且一开始使用十六进制表示法(一行三个碱基!)也让我感到很不舒服。我个人喜欢
&0xff
。我发现它更清晰,特别是因为这段代码可能被不太熟悉Python的
%
行为如何偏离C的人读到了。(
%256
在C中不起作用。)@user2357112supportsMonica我明白了。
&0xFF
是否等同于
%(0xFF+1)
?这在大多数语言中都适用吗?或者这是python的东西?@samuelbrody1249
&0xFF
(按位和)在这种情况下也适用,是的,几乎可以肯定是更好的选择。我不打算编辑我的答案,因为它将基本上改变整个事情(我在写它时没有想到按位),但希望任何感兴趣的人都能阅读下面的评论)。如果我们考虑像C这样的静态类型语言(在这种情况下,您只需执行
*((unsigned char*)&char)
,而无需直接进行位操作),这是一个没有实际意义的问题,但它应该在动态类型语言(如python和javascript)中工作。