Queen
Queen

Reputation: 185

Optimization - how to store "bits" in memory?

I'm a newbie in Python and I have a problem with storing information. I've got a task from my 'mentor' and I don't know how to do that. I have array with numbers 0 and 1, e.g.

a=[1,1,1,0] 

I know that's integers, but he told I should keep it as bits. I was trying to convert my variable to number e.g:

a = 14 and then ab = bin(14).

But when I'm using sys.getsizeof() ab is bigger than a. I was trying to use bytearray() but I don't understand it, too. I was thinking that I know how a computer works, but that makes me confused.

How should I keep bits? What should I use? What should I read to understand it? and how to measure how big is my variable (sys.getsizeof() is okay for that? Or should I write it to a binary file?). We doing it to optimize memory.

Upvotes: 0

Views: 452

Answers (1)

martineau
martineau

Reputation: 123463

I'm not sure I understand the goal, but here's a guess:

def convert(bits):
    val = 0
    for bit in bits:
        val = (val << 1) | bit
    return val

a = [1, 1, 1, 0]
ab = convert(a)
print(ab, bin(ab))  # -> 14 0b1110

The result stored in ab is a single Python integer, which have varying lengths depending on how many bits are required to hold the number. The code above will handle any number of bits (but you could put a limit on it).

Upvotes: 2

Related Questions