Code Snippet: Getting variables in python with a defined size of bits

For a new project I needed to do some low level programming in python in which I needed data types with a defined size of bits. Normally python organizes the size of your variables, so that you cannot make your variable a defined 8bit , 16bit, 24bit, etc. integer, but with some bitwise operations you can create variables with a certain size in bits.

Let’s say you want to have a 8bit integer value. 8bit is the equivalent of 2^8 or 256, so all you have to do is make your integer the maximum possible of the bit width you want to have.

uint8 = 255      # Create a 8bit wide integer variable
                 # This lets uint8 be 11111111 in binary notation
uint16 = 65535   # Create a 16bit wide integer variable
                 # This lets uint8 be 11111111111111111 in binary notation

Okay, now let’s say you have two bytes from a stream or file or something and you need to concatenate them to a 16bit integer. In this case you can do the following:

arr = [255, 67]
int16 = 255 # Reserve the first 8bits
int16 |= arr[0] # Set the first 8bits to the first byte value
int16 <<= 8 # Extend the data type to 16bits
int16 |= arr[1] # Set the lower 8bits

After that operation int16 is a 16bit integer value. To get a 24bit, 32bit, 64bit, etc. variable you just have to repeat extending and setting the variable until it has your desired length in bits or do it in a loop (which would be the smarter idea).

Similar Posts: