tian tong
tian tong

Reputation: 833

python how to transfer between a list of integers and string of bits?

I have a list of integers, each integer in range [0,255]. I want to transfer this into a string of bits. Each integer use 8 bits to represent. After I handle string of bits, I want to transfer it into a list of integers, every 8-bit to a integer. How to do it?

Upvotes: 0

Views: 217

Answers (2)

Zhenhao Chen
Zhenhao Chen

Reputation: 535

You don't need external library. Use python's built-in function.

integer to binary:

i = 100
print "{0:08b}".format(i)

binary to integer:

b = "01100100"
print int(b, 2)

If you need to build a large bit array, then using bitarray module is good, as what you did in your answer:

bits = bitarray()
for i in pixels: bits.extend("{0:08b}".format(i))

Upvotes: 1

tian tong
tian tong

Reputation: 833

I have got the answer. This is my answer:

from PIL import Image
from bitarray import bitarray
from bitstring import BitArray


class Compress:
    def readFile(self, filename):
        self.img = Image.open(filename)
        self.pixels = list(self.img.getdata())  # a list of int--[0,255]

    def __toBitArray__(self):
        self.bits = bitarray()
        for i in self.pixels:
            self.bits.extend(BitArray(uint=i, length=8).bin)
        print(self.bits.length())

    def saveFile(self, filename):
        p = []
        for i in range(self.bits.length()//8):
            b = self.bits[i*8:i*8+8].to01()
        p.append(BitArray(bin=b).uint)
        self.img.putdata(p)
        self.img.save(filename)
        self.img.close()


if __name__ == '__main__':
    c = Compress()
    c.readFile('num.bmp')
    c.__toBitArray__()
    c.saveFile('test.bmp')

Upvotes: 0

Related Questions