Search code examples
pythonbyte

How to make a cyclic reset of a byte through zero by sum?


I created bytes. Also I try to make addition of bytes. But I am getting an error

ValueError: byte must be in range(0, 256)

Instead of an error, I expect a loop, for example 255+2 = 1. How can I do it like in C?

bytes_ = bytearray([0xFF, 0xFF, 0xFF])  
bytes_[0] = bytes_[0] + 1
bytes_[1] = bytes_[1] + 2
bytes_[2] = bytes_[2] + 3
print(bytes_) 

Solution

  • Usually adding relies on bitwise addition of the bits using the carry flag in a register of the CPU. The excessive bits are skipped (the value can be seen in the carry flag) say in an 8 bit register, so only the numbers 0 to 255 are represented. See here for some internals.

    Python bytes don't work like a CPU register.

    This is what at least "cyles" through a byte:

    byte=0xF9
    for i in range(10):
      byte = (byte+1) & 255
      print(byte)
    

    You normally add, using integer arithmetics and cut off all excessive bits by using a bitwise AND: & 255.

    Output:

    250
    251
    252
    253
    254
    255
    0
    1
    2
    3
    

    Your example modified:

    bytes_ = bytearray([0xF9])
    for i in range(10):
      bytes_[0] = (bytes_[0] + 1) & 255
      print(bytes_[0])
    

    Gives the same output.