Implementing an 8 bit fixed point register

Terry Reedy tjreedy at
Tue Jul 1 21:14:15 CEST 2008

nickooooola wrote:
> Hello to all
> I'm about to write a simulator for a microcontroller in python
> (why python? because I love it!!!)
> but I have a problem.
> The registry of this processor are all 8 bit long (and 10 bit for some
> other strange register)
> and I need to simulate the fixed point behaviour of the register,
> and to access the single bit.

In Python3, I would use a (mutable) bytearray.

IDLE 3.0b1
 >>> reg1 = bytearray((0,)*8) # or *10 for 10 bits
 >>> reg1
 >>> reg1[1]=1
 >>> reg1[1]
 >>> tuple(reg1)
(0, 1, 0, 0, 0, 0, 0, 0)

A bytearray subclass could enforce that all 'bits' (stored as bytes) are 
0 or 1, have a customized representation to your taste, and add methods 
like .flipall().

The overhead of using 8 bytes instead of 1 to hold the object value is 
actually small compared to the minimum object size of 16 bytes (on Win32XP).

 >>> sys.getsizeof(reg1)

In Python2.x, you can use the array module to make equivalent mutable 
arrays of chars.

Terry Jan Reedy

More information about the Python-list mailing list