开发者

Transform bits into byte series

Given a Python integer which is within the size of 4 bits, how does one transform it – with bitwise arithmetic instead of string processing – into an integer within the size of 4 bytes, for which each bit in the original corresponds to a byte which is the bit repeated 8 times?

For example: 0b1011 should become 0b111111110000000011111111111开发者_JAVA技巧11111


With apologies to ncoghlan:

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

Then just index this list with the nibble you want to transform:

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


I'd just do a loop:

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


The following recursive solution uses only addition, left/right shift operators and bitwise & operator with integers:

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)

Or, as a one-liner:

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

Examples:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜