Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

upul jayalath
1,295 PointsThe number of bits needed to represent an integer- using log base 2?
Please help me to understand this problem.
The number of bits needed to represent an integer n is given by rounding down log2(n) and then adding 1.
For example log2(100) is about 6.643856. Rounding this down and then adding 1, we see that we need 7 bits to represent 100.
For the 8 we have to apply the above method again (3+1), ie we need 4 bits to represent 8.
math.log(8,2) 3.0
But when I use the above method to find out the number of bits needed to represent sys.maxsize (9,223,372,036,854,775,807) like
math.log(sys.maxsize,2) 63
The above value directly gives the answer, ie we need 63 bits to represent sys.maxsize (9,223,372,036,854,775,807)
Can you explain why?
2 Answers

Jon Mirow
9,864 PointsHi there!
Love that you're experimenting with it! The reason is the value stored in sys.maxsize. It already takes this into account.
From the python docs (https://docs.python.org/3/library/sys.html#sys.maxsize):
An integer giving the maximum value a variable of type Py_ssize_t can take. Itβs usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform.
Hope it helps!

upul jayalath
1,295 PointsHI Jon
Thanks, I understand it. But my confusion is;
When i use a small number (say 8) log base 2 of 8 is 3 then we add 1 to 3 and the result is 4 This 4 is the number of bits needed to represent 8
When i use a larger number (say 9,223,372,036,854,775,807 or 9,223,372,036,854,775,806) log base 2 of this 9,223,372,036,854,775,807 is 63 Here to get the number of bits i dont need to add 1 It directly gives the number of bits (63) to represent this big number 9,223,372,036,854,775,807.
This means we cant apply the following theory ALWAYS for every integer, is that so? "The number of bits needed to represent an integer n is given by rounding down log2(n) and then adding 1"
Thanks and regards Jay.