This function should convert your numbers to look like hardware integers. Depending on your application, you might need to apply this function between each stage 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 shortcut functions may come in handy for "casting" values to their 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 might use them, a bug can reproduced that one might see in C. If one were to write a for loop using a byte to print out 0 - 255, the loop might 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()