Search code examples
pythoncrolloveruint8t

uint8_t rollover in Python? What is the best or most elegant way?


in C, I can do the following:

uint8_t number;
number++;

Note: If the number is >255, then is rolls over to 0.

How can I do it Python?

number += 1
if number>255:
    number = 0

This looks for me not the optimal or pythonic way. Any ideas?


Solution

  • You can freely do all standard mathematic operations and whenever you need the output in byte range just use number % 256 instead of the number. Or you can extend this approach to a class and define all standard operators (__add__(), __neg__(),...) there. Or you can use c_ubyte datatype from ctypes module.