Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum number of bits to represent number

What is the most efficient way to find out how many bits are needed to represent some random int number? For example number 30,000 is represented binary with

111010100110000

So it needs 15 bits

like image 522
Marka Avatar asked Sep 10 '12 10:09

Marka


People also ask

How many bits are required to store a number?

Two base-2 digits (or binary digits, or bit s) can hold values 00 through 11, so 4; with three bits 00 through 111, so 8; with four bits 00 through 1111, so 16; with eight (a byte) 00000000 through 11111111, so 256.

Can you represent in 8 bits?

The largest number you can represent with 8 bits is 11111111, or 255 in decimal notation. Since 00000000 is the smallest, you can represent 256 things with a byte. (Remember, a bite is just a pattern. It can represent a letter or a shade of green.)

What is the minimum number of bits required to represent the number 45?

As u can see we have used total 6 right shift operation ( >> ) to get 0, so 6 will be required number of minimum bits to represent a number in binary. Enter any Number 45 Number of bits : 6 Process returned 0 (0x0) execution time : 1.721 s Press any key to continue.


3 Answers

You may try:

Math.Floor(Math.Log(30000, 2)) + 1

or

(int) Math.Log(30000, 2) + 1
like image 51
petro.sidlovskyy Avatar answered Sep 21 '22 20:09

petro.sidlovskyy


int v = 30000; // 32-bit word to find the log base 2 of
int r = 0; // r will be lg(v)

while ( (v >>= 1) != 0) // unroll for more speed...
{
  r++;
}

For more advanced methods, see here http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious

Note that this computes the index of the leftmost set bit (14 for 30000). If you want the number of bits, just add 1.

like image 35
Henrik Avatar answered Sep 19 '22 20:09

Henrik


Try log(number)/log(2). Then round it up to the next whole number.

like image 30
Daniel Lidström Avatar answered Sep 21 '22 20:09

Daniel Lidström