根据消息改变位

时间:2013-10-03 03:29:33

标签: python tuples pixel bitwise-operators

我在列表中有一个三元素tuple,在8位二进制文​​件中有一条消息

list = [(15,103,255)]

message = '0110100001100101011011000110110001101111'

我需要一个同时占用3位消息的函数,然后将每个元素从tuple转换为二进制,并将其前3位替换为消息中的位。

例如:步骤1. a = message[0:3]

         a = '011'

第2步:b = '{0:08b}'.format(15)

         b = '00001111'

第3步:c = '01101111'

第4步:d = int(c,2)

     d = 111

新列表应为

new_list = [(111,71,31)]

1 个答案:

答案 0 :(得分:2)

这是一种方式,猜测一些不清楚的事情。我把它塞进一堂课,以便更容易改变:

class BitFiddler:
    def __init__(self, bitstring):
        self.bitstring = bitstring
        self.i = 0

    def fiddle(self, value):
        nextbits = self.bitstring[self.i : self.i + 3]
        self.i += 3
        nextbits = int(nextbits, 2)
        return (value & 0x1f) | (nextbits << 5)

thelist =  [(15,103,255)]
message =  '0110100001100101011011000110110001101111'
bf = BitFiddler(message)
print [tuple(bf.fiddle(value) for value in thelist[0])]

输出:

[(111, 71, 31)]

作为1-liner:

print [tuple((v & 0x1f) | (int(message[i:i+3], 2) << 5)
             for v, i in zip(thelist[0], range(0, len(message), 3)))]