Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to find, via Python code, the number of bits needed to store an integer, and how to generate its binary representation. It does this for integers from 0 to 256.

More details and full output here:

Python, 12 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12``` ```# int_bit_length_and_binary_repr.py # Purpose: For integers from 0 to 256, print the number of # bits needed to represent them, and their values in binary. # Author: Vasudev Ram # Website: https://vasudevram.github.io # Product store on Gumroad: https://gumroad.com/vasudevram # Blog: https://jugad2.blogspot.com # Twitter: @vasudevram for an_int in range(0, 256 + 1): print an_int, "takes", an_int.bit_length(), "bits to represent,", print "and equals", bin(an_int), "in binary" ```

A user would want to do this task, to find out how many bits it takes to represent any specific integer (in the range shown, and the range can easily be extended by changing the for loop upper limit), and also to see the binary representation of that integer. This is useful for a lot of programming purposes.

More details and full output here: