将整数转换为二进制,然后在python中进行左移位

Inv*_*nce 6 python int hex bit-shift bin

我有一个来自文本文件的整数输入,我需要将其转换为二进制并进行左移位12位.

所以,如果我的数字是6.二进制是110.我的最终输出应该是1100亿,位移了12位.

我试过了:

i = 6
h = int(bin(i)[2:])<<12
Run Code Online (Sandbox Code Playgroud)

但是,这会产生错误的输出.问题是bin(i)返回一个字符串,所以我不得不将它转换为int但是然后使用shift运算符移动整数而不是二进制.

Joh*_*han 5

您可以在转换为二进制之前进行位移,因为位移不关心整数的基数(根据定义,位移是在2的基数中完成的).

i = 6 << 12
answer = bin(i)[2:]
Run Code Online (Sandbox Code Playgroud)

编辑:来自@guidot的替代二进制转换

i = 6 << 12
answer = "{:b}".format(i)
Run Code Online (Sandbox Code Playgroud)

额外的转换

只是为了它的乐趣,这里有一些其他方法来移位数字:

i = 6 * (2**12) # This will convert into 6 * 2^12
answer = "{:b}".format(i)
Run Code Online (Sandbox Code Playgroud)

位移将使数值加倍,因此通过将位移与功率二相乘,我们可以实现相同的目标:

> print(6 << 12)
24576
> print(6 * 2**12)
24576
Run Code Online (Sandbox Code Playgroud)

如果您知道只想将值加倍,那么使用位移通常会更好.

您还可以将其转换为二进制,然后添加13个尾随零,这是一种实现相同功能的时髦方式:

i = 6 # Notice: No operation here this time
answer = "{:b}".format(i) + ('0' * 12)
Run Code Online (Sandbox Code Playgroud)

也许不建议使用最后一种方法,但它说明了(左)位移的工作原理.