Python bit functions on int (bit_length, to_bytes and from_bytes)
The int type implements the numbers.Integral abstract base class.
1. int.bit_length()
Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros.
Code to demonstrate
num = 7print(num.bit_length()) num = -7print(num.bit_length()) |
3 3
2. int.to_bytes(length, byteorder, *, signed=False)
Return an array of bytes representing an integer.
# Returns byte representation of 1024 in a # big endian machine. print((1024).to_bytes(2, byteorder ='big')) |
b'\x04\x00'
3. int.from_bytes(bytes, byteorder, *, signed=False)
Returns the integer represented by the given array of bytes.
# Returns integer value of '\x00\x10' in big endian machine. print(int.from_bytes(b'\x00\x10', byteorder ='big')) |
16
Recommended Posts:
- Python | Numpy matrix.tobytes()
- Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
- Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
- Mathematical Functions in Python | Set 4 (Special Functions and Constants)
- Mathematical Functions in Python | Set 1 (Numeric Functions)
- Log functions in Python
- Functions in Python
- First Class functions in Python
- Iterator Functions in Python | Set 1
- Partial Functions in Python
- Operator Functions in Python | Set 1
- Operator Functions in Python | Set 2
- Decimal Functions in Python | Set 1
- Array in Python | Set 1 (Introduction and Functions)
- Array in Python | Set 2 (Important Functions)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



