Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number of 1's in 32 bit number

I am lookin for a method to have number of 1's in 32 bit number without using a loop in between. can any body help me and provide me the code or algorithm to do so. Thanks in advance.

like image 841
Abhi Avatar asked Sep 22 '09 05:09

Abhi


People also ask

How many numbers can 32 bits make?

A 32-bit integer limit allows for 4,294,967,296 (232 2 3 2 ) pieces of data. If storing signed integers, this would range from -2,147,483,648 to 2,147,483,647.

What is a 32-bit whole number?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.

Are integers always 32-bit?

int is always 32 bits wide. sizeof(T) represents the number of 8-bit bytes (octets) needed to store a variable of type T . (This is false because if say char is 32 bits, then sizeof(T) measures in 32-bit words.) We can use int everywhere in a program and ignore nuanced types like size_t , uint32_t , etc.

What is the smallest 32-bit binary number?

This means that the highest value is represented as 01111111 (+127), and the lowest value is represented as 10000000 (-128). 11111111 represents -1. The same principle applies to 32-bit signed integers, just with bigger place values (specifically, -2147483648 for the sign bit).


5 Answers

See Integer.bitCount(int). You can refer to the source code if you want to see how it works; many of the Integer class's bit twiddling routines are taken from Hacker's Delight.

like image 93
erickson Avatar answered Sep 19 '22 15:09

erickson


See the canonical reference: Bit Twiddling Hacks

like image 43
Mitch Wheat Avatar answered Sep 21 '22 15:09

Mitch Wheat


Short, obscenely optimized answer (in C):

int pop(unsigned x) {
   x = x - ((x >> 1) & 0x55555555);
   x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
   x = (x + (x >> 4)) & 0x0F0F0F0F;
   x = x + (x >> 8);
   x = x + (x >> 16);
   return x & 0x0000003F;
}

To see why this magic works, see The Quest for an Accelerated Population Count by Henry S. Warren, Jr. chapter 10 in Beautiful Code.

like image 22
lindelof Avatar answered Sep 21 '22 15:09

lindelof


Split the 32 bit number into four 8 bit numbers (see bit shifting operator, casting etc.)

Then use a lookup with 256 entries that converts the 8 bit number into a count of bits set. Add the four results, presto!

Also, see what Mitch Wheat said - bit fiddling can be a lot of fun ;)

like image 20
Daren Thomas Avatar answered Sep 20 '22 15:09

Daren Thomas


You can define it recursively:

int bitcount(int x) {
  return (x==0) ? 0 : (x & 1 + bitcount(x/2));
}

The code above is not tested, and probably only works for x>=0. Hopefully, you will get the idea anyways...

like image 22
SteinNorheim Avatar answered Sep 18 '22 15:09

SteinNorheim