nickooooola wrote: > Hello to all > I'm about to write a simulator for a microcontroller in python > (why python? because I love it!!!) [...] > 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. > > f.x. (this is a pseudo python session, only for understanding) > >>>> reg1 = fixed_int(8) >>>> reg2 = fixed_int(10) >>>> reg1[0].set() > or >>>> reg1[0] = 1 # or True? how to rapresent a binary bit >>>> reg1[0] > 1 >>>> reg1[1] > 0 >>>> reg1[9] > <exception .... blah blah not in range> >>>> reg2 = 0x7FE # in binary 11111111110 , or 11 bit long >>>> reg2 > 0x7FE > #or 1111111110, the memorization truncate the upper bits ( or perhaps > generate an exception?) >>>> reg2 += 0x02 #the result is 10000000000, again not contained in 10 bit >>>> reg2 > 0x00 > # truncated again >>>> myprocessor.flags['z'] > 1 > # or True? Z flag indicated an overflow in arithmetic operations > > Is possibile to do so in python?
I did this for a PIC, and generally just used brute force, e.g. temp = reg2 + 0x02 reg2 = temp & 0xFF if temp & 0x100: flags |= CARRY_MASK else: flags &= ~CARRY_MASK if temp & 0xFF: flags &= ~ZERO_MASK else: flags |= ZERO_MASK Since it was a PIC, and there were only a half-dozen arithmetic/logical operations, the code stayed in this form. With something bigger, it would have been attractive to wrap these operations up in a class, as you suggest.. (just a sketch) .. class fixed_register (object): def __init__ (self, size, val=0): self.mask = ~(-1 << size) self.ovfmask = 1 << size self.val = val & self.mask with appropriate __add__, __sub__, etc. Perhaps __getitem__, __setitem__ to manipulate bits. Good Luck, Mel. -- http://mail.python.org/mailman/listinfo/python-list