Python bit functions on int with examples
In this tutorial, we are going to learn about some bit functions on int in Python i. e. bit_length(), to_bytes() and from_bytes(). Let’s discuss these functions one by one.
This function returns the number of bits required to represent a number in binary. It excludes the sign bit and all the leading zeroes. See the given example code to understand the working of this function.
int1 = 12 print(int1.bit_length()) int2 = 1 print(int2.bit_length()) int3 = -1 print(int3.bit_length())
The output for the example program:
4 1 1
As its name suggests, this function returns an array of bytes that represent an integer. Have a look at the given example code that explains its working.
int1 = 12 print(int1.to_bytes(2, byteorder = 'big')) int2 = 1 print(int2.to_bytes(2, byteorder = 'big'))
In the above code, there are two arguments in to_bytes() function. value 2 specifies the length and ‘big’ specifies that the order of bytes is big-endian.
To use this function with negative values we will need to use the third argument as shown below.
int1 = -1 print(int1.to_bytes(2, byteorder = 'big', signed = True))
When we make signed = True, the function accepts negative values, otherwise, it throws an error. The default value for the signed parameter is False.
This is the reverse of the to_bytes() function. It takes an array of bytes as input and converts it into an integer. See the below code.
print(int.from_bytes(b'\x00\x0c', byteorder = 'big')) print(int.from_bytes(b'\x00\x01', byteorder = 'big'))
For negative numbers, make the signed parameter as True as shown here.
print(int.from_bytes(b'\xff\xff', byteorder = 'big', signed = True))
Hope this article was helpful. Thank you.