6

如何将 intn转换为二进制并测试生成的二进制数的每一位?

经过大量谷歌搜索后,我得到了以下信息:

def check_bit_positions(n, p1, p2):
    print int(str(n),2)

但是我得到一个错误invalid literal for int() with base 2。让我知道如何获得输入数字的二进制形式并在位置p1和测试每个位p2

编辑:

binary = '{0:b}'.format(n)
if list(binary)[p1] == list(binary)[p2]:
     print "true"
 else:
     print "false"

上面的代码现在可以工作了,但是我如何从列表末尾检查位置 p1 和 p2 呢?

4

3 回答 3

7

使用bin()功能:

>>> bin(5)
'0b101'

str.format

>>> '{0:04b}'.format(5)
'0101'
于 2013-08-07T18:54:14.773 回答
4

这是我编写的用于检查数字的第 n 位的快速函数:

def check_nth_bit(num, n):
    return (num>>n)&1

Basically, you bitshift the number n times to the right, which would put the nth digit in the rightmost position, and by bitwise and-ing the new number with 1 (which is all 0's except for in the rightmost position), you can check if that bit is a 1 or a 0. So, you can call this function on num with p1 and p2 and compare the results.

EDIT: This will be p1 and p2 from the end of the number (least-significant bit), not the beginning.

于 2013-08-07T18:57:45.200 回答
3

您可以使用format

>>> format(10, 'b')
'1010'

int用于将数字从任何基数转换为基数 10,并且您试图使用它将整数转换为错误的二进制数。

>>> int('1010', 2)
10
>>> int('20', 2)
Traceback (most recent call last):
  File "<ipython-input-3-05fc7296a37e>", line 1, in <module>
    int('20', 2)
ValueError: invalid literal for int() with base 2: '20'
于 2013-08-07T18:55:40.527 回答