I am looking for way to determine the number of characters my binary value takes up.
For example if my values binary values were 4, 20, and 60 I'd get the following results:
bin(4), 0b100 = 3
bin(20), 0b10100 = 5
bin(60), 0b111100 = 6
A positive integer n has b bits when 2b-1 ≤ n ≤ 2b – 1. So The number of bits required to represent an integer n is :
floor(log n)+1 # note that base of log is 2
And since you have 0b at the leading you need to add 2 to aforementioned formula.
So it would be :
floor(log n) + 3
And in python you can use math module like following:
math.floor(math.log(n, 2)) + 3
Example :
>>> math.floor(math.log(10, 2)) + 3
6.0
>>>
>>> len(bin(10))
6
>>> math.floor(math.log(77, 2)) + 3
9.0
>>> len(bin(77))
9
As a more Pythonic way you can also use int.bit_length which returns the number of bits needs to represent an integer object. So for get the number of require characters you can add it with 2 :
int.bit_length() + 2
floor(log(n, 2)) + 1 isn't a good idea if you need correct results for larger inputs. For example, it gives the wrong result on my machine for 562949953421311 (the correct answer is 49, but on my machine this formula gives 50). In recent Python versions, you can use log2, which is a bit more accurate than log(n, 2), but there's really no point when the bit_length method is available.bit_length function.bit_length is a method and should be called
x.bit_length().