Simulating integer overflow in Python

前端 未结 5 1495
無奈伤痛
無奈伤痛 2020-12-06 18:04

Python 2 has two integer datatypes int and long, and automatically converts between them as necessary, especially in order to avoid integer overflo

5条回答
  •  佛祖请我去吃肉
    2020-12-06 18:51

    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()
    

提交回复
热议问题