Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many bits do you need to store a positive integer?

Tags:

integer

binary

How many bits would you need to store a positive integer for example in the billions? Would you have to use the log2 N to find this out?

like image 949
user1647008 Avatar asked Sep 04 '12 18:09

user1647008


People also ask

How many bits does it take to store an integer?

1 Integers. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.

What can be stored in 4 bits?

With 4 bits, the maximum possible number is binary 1111 or decimal 15. The maximum decimal number that can be represented with 1 byte is 255 or 11111111. An 8-bit word greatly restricts the range of numbers that can be accommodated.

How many values can 1 bits store?

A single bit can only represent two different values.

How many values can 4 bits store?

With 4 bits, it is possible to create 16 different values. All single-digit hexadecimal numbers can be written with four bits. Binary-coded decimal is a digital encoding method for numbers using decimal notation, with each decimal digit represented by four bits.


2 Answers

Yes. the maximal number stored in k bits is 2^k-1, since there is 2^k options for the bits, and one of them is zero.
Therefore, the number of bits required to store a number N is log2(N), but since there is no half bit, you need to round it up to the cloest integer above.

Note: if you need to include negative numbers, there must be one more bit for the sign.

like image 29
LeeNeverGup Avatar answered Sep 20 '22 15:09

LeeNeverGup


Since I've seen the answer reported incorrectly so many times, I thought I would post the correct answer.

The number of bits needed to represent the positive integer n is

bits = floor( log2(n) + 1 )

where log2 means log base 2.

like image 170
bradwilder31415 Avatar answered Sep 19 '22 15:09

bradwilder31415