python - 在二进制数的位之间迭代

标签 python python-3.x

如何在 python 3 中迭代和评估给定特定二进制数的每个位的值?

例如:

00010011 
--------------------
bit position | value
--------------------
[0]            false (0)
[1]            false (0)
[2]            false (0)
[3]            true  (1)
[4]            false (0)
[5]            false (0)
[6]            true  (1)
[7]            true  (1)

最佳答案

最好用bitwise operators使用位时:

number = 19

num_bits = 8
bits = [(number >> bit) & 1 for bit in range(num_bits - 1, -1, -1)]

这为您提供了一个包含 8 个数字的列表:[0, 0, 0, 1, 0, 0, 1, 1]。遍历它并打印任何需要的东西:

for position, bit in enumerate(bits):
    print '%d  %5r (%d)' % (position, bool(bit), bit)

关于python - 在二进制数的位之间迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16659944/

相关文章:

python - 在 TensorFlow 中制作列表并附加到列表中

python - 有没有办法同时对多个文件使用 COPY?

python - 根据特定条件 pandas 增加列中的计数器

Python将一个变量内的多个列表合并为一个列表

python-3.x - 对新的线性 SVM 数据帧进行分类时出错

c# - 选择编程语言的建议

python - 非英文文本python不可读

python-3.x - 多个输入和 "SyntaxError: unexpected EOF while parsing"

python - TypeError : can't concat bytes to str时如何转换为字节

python - 把一个名词变成它的代词