use*_*301 2 python bit-manipulation
我试图在整数的16位二进制表示上使用左移运算符
编写的代码如下:
def showbits(x):
return bin(x)[2:].zfill(16)
i=5225
print "Decimal %d is same as binary" % (i)
print showbits(i)
for j in range(0,5,1):
k=i<<j
print "%d right shift % gives" % (i,j)
print showbits(k)
Run Code Online (Sandbox Code Playgroud)
输出:
Decimal 5225 is same as binary
0001010001101001
5225 right shift 0ives
0001010001101001
5225 right shift 1ives
0010100011010010
5225 right shift 2ives
0101000110100100
5225 right shift 3ives
1010001101001000
5225 right shift 4ives
10100011010010000
Run Code Online (Sandbox Code Playgroud)
主要的问题是,当它移动前导'1'时,它并没有消失,而是在增加一点......
任何解决方案?
您将使用按位AND 屏蔽结果值&:
mask = 2 ** 16 - 1
k = (i << j) & mask
Run Code Online (Sandbox Code Playgroud)
这16是你想要的位宽; 您可以使用i.bit_length()它将其限制为所需的最小大小i,但这意味着任何左移都会丢弃位.
掩码形成一系列1与原始值具有相同宽度的位; 该&操作将任何位设置为0 以外的位:
>>> 0b1010 & 0b111
2
>>> format(0b1010 & 0b111, '04b')
'0010'
Run Code Online (Sandbox Code Playgroud)
一些旁注:
您似乎忘记了d调试打印中的a:
print "%d left shift %d gives" % (i,j)
Run Code Online (Sandbox Code Playgroud)
有一个孤独的%存在与合并g进行gives,使%g(浮点格式).
您可以使用:
def showbits(x):
return format(x, '016b')
Run Code Online (Sandbox Code Playgroud)
格式化到一个0填充16个字符宽二进制表示的整数,而不的0b前缀.