This function should convert your numbers so that they look like hardware integers. Depending on your application, you may need to apply this function between each step of your operations.
def correct(value, bits, signed): base = 1 << bits value %= base return value - base if signed and value.bit_length() == bits else value
The following quick access functions may be useful for cast values โโin the appropriate range:
byte, sbyte, word, sword, dword, sdword, qword, sqword = ( lambda v: correct(v, 8, False), lambda v: correct(v, 8, True), lambda v: correct(v, 16, False), lambda v: correct(v, 16, True), lambda v: correct(v, 32, False), lambda v: correct(v, 32, True), lambda v: correct(v, 64, False), lambda v: correct(v, 64, True) )
As an example of how you can use them, you can reproduce the error that can be seen in C. If you need to write a for loop using print bytes 0 - 255, the cycle will never end. The following program demonstrates this problem:
#! /usr/bin/env python3 def main(): counter = 0 while counter < 256: print(counter) counter = byte(counter + 1) def correct(value, bits, signed): base = 1 << bits value %= base return value - base if signed and value.bit_length() == bits else value byte, sbyte, word, sword, dword, sdword, qword, sqword = ( lambda v: correct(v, 8, False), lambda v: correct(v, 8, True), lambda v: correct(v, 16, False), lambda v: correct(v, 16, True), lambda v: correct(v, 32, False), lambda v: correct(v, 32, True), lambda v: correct(v, 64, False), lambda v: correct(v, 64, True) ) if __name__ == '__main__': main()