Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

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) gives 63

The above value directly gives the answer, ie we need 63 bits to represent sys.maxsize (9,223,372,036,854,775,807)

math.log(8,2) gives 3.0

For the 8 we have to apply the above method again (3+1), ie we need 4 bits to represent 8.

Can you explain why?

What I have tried:

math.log(8,2) gives 3.0 (but number of bits needed is 4)


math.log(sys.maxsize,2) gives 63 (here the number of bits needed is 63)
Posted
Updated 5-Apr-18 15:35pm
Comments
gggustafson 5-Apr-18 22:35pm    
Although not conversant in Python, most number systems have a largest positive value that is one bit less in length than the largest negative number (the leading sign bit)
Member 13765066 5-Apr-18 22:54pm    
If i explain it further;

For a small integer like 8, we take log base2 of 8. The result is 3, then we add 1 to 3 and the result is 4. So 4 bits are needed to represent 8.

For a large integer like 9223372036854775807, we take log base2 of 9223372036854775807. The result is 63. Here we don't need to add 1. It directly gives the number of bits, that is 63 bits are needed to represent 9223372036854775807.

In theory in python, it says that the number of bits needed to represent an integer n is given by rounding down log2(n) and then adding 1. But this seems not correct for a bigger integer?? This is what i couldnt understand.
gggustafson 8-Apr-18 13:55pm    
Did it occur to you that log base 2 ( 9223372036854775807 ) is 62.999999999999999999843582690243 and that floor ( log base 2 ( 62.999999999999999999843582690243 ) ) is 62? Therefore you need to add 1 as the rule specifies.
PIEBALDconsult 5-Apr-18 22:35pm    
Why would you not use the Ceiling?

1 solution

Quote:
Please help me to understand this problem.

How to say ?
Just convert all those numbers in base 2 (radix), and count the number of digits, it is the number of bits.
Quote:
It directly gives the number of bits, that is 63 bits are needed to represent .

That is because 63 is rounded value of smething like 62.999...
 
Share this answer
 
v2
Comments
gggustafson 8-Apr-18 13:59pm    
The theory is not wrong; your precision of log base 2 is not or you accidentally throw away precision (by rounding) before taking the floor.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900