3

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
1
  • 4
    Also, in recent versions, x.bit_length(). Commented Feb 13, 2016 at 16:43

2 Answers 2

3
a = 20
a.bit_length()
>> 5
Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

Using 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.
@MarkDickinsonThanks for edit. Yep that's because of the restricts in calculating the floating point numbers. But at first I thought OP is looking fora mathematical approach and actually I've missed bit_length function.
bit_length is a method and should be called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.