将位转换为字节序列

时间:2011-02-21 02:32:06

标签: python bit-manipulation

给定一个大小为4位的Python整数,如何将其变换 - 使用按位算术而不是字符串处理 - 转换为4字节大小的整数,原始中的每个位对应于字节是重复8次的位?

例如:0b1011应该成为0b11111111000000001111111111111111

3 个答案:

答案 0 :(得分:4)

向ncoghlan道歉:

expanded_bits = [
    0b00000000000000000000000000000000,
    0b00000000000000000000000011111111,
    0b00000000000000001111111100000000,
    0b00000000000000001111111111111111,
    0b00000000111111110000000000000000,
    0b00000000111111110000000011111111,
    0b00000000111111111111111100000000,
    0b00000000111111111111111111111111,
    0b11111111000000000000000000000000,
    0b11111111000000000000000011111111,
    0b11111111000000001111111100000000,
    0b11111111000000001111111111111111,
    0b11111111111111110000000000000000,
    0b11111111111111110000000011111111,
    0b11111111111111111111111100000000,
    0b11111111111111111111111111111111,
    ]

然后用你要变换的半字节索引这个列表:

>>> bin(expanded_bits[0b1011])
"0b11111111000000001111111111111111"

答案 1 :(得分:1)

我只是做一个循环:

x = 0b1011
y = 0
for i in range(4):
    if x & (1 << i):
        y |= (255 << (i * 8))
print "%x" % y

答案 2 :(得分:0)

以下递归解决方案仅使用加法,左/右移位运算符和按位&amp;整数运算符:

def xform_rec(n):
    if n == 0:
        return 0
    else:
        if 0 == n & 0b1:
            return xform_rec(n >> 1) << 8
        else:
            return 0b11111111 + (xform_rec(n >> 1) << 8)

或者,作为一个单行:

def xform_rec(n):
    return 0 if n == 0 else (0 if 0 == n & 0b1 else 0b11111111) + (xform_rec(n >> 1) << 8)

示例:

>>> print bin(xform_rec(0b1011))
0b11111111000000001111111111111111
>>> print bin(xform_rec(0b0000))
0b0
>>> print bin(xform_rec(0b1111))
0b11111111111111111111111111111111)