473,387 Members | 1,590 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Bit count of an integer

I read some old posts, they did this task in very different ways. How
is the following one?

Thank you for your time.
/
************************************************** *****************************
* Count the bit set in an integer. eg. integer: 0x01101011, bitcount:
5

************************************************** ****************************/

int bitcount(int i)
{
unsigned int cnt = 0, MASK;

for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
}

Nov 5 '07 #1
11 6499
"lovecreatesbea...@gmail.com" <lo***************@gmail.comwrites:
I read some old posts, they did this task in very different ways. How
is the following one?

Thank you for your time.
/
************************************************** *****************************
* Count the bit set in an integer. eg. integer: 0x01101011, bitcount:
5

************************************************** ****************************/

int bitcount(int i)
{
unsigned int cnt = 0, MASK;

for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
}
Someone else will tell you about left shifting out of range ( I reckon
its probably fine with an unsigned int) but I would remove the
comparison to MASK and put MASK in lower case since upper case tends to
indicate a constant/#define.
Nov 5 '07 #2
lovecreatesbea...@gmail.com wrote:
I read some old posts, they did this task in very different ways. How
is the following one?
/*
* Count the bit set in an integer. eg. integer: 0x01101011, bitcount: 5
*/

int bitcount(int i)
{
unsigned int cnt = 0, MASK;

for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
}
Leaving aside the problems of reading this code aloud (I used to be a
trainer and I know the pitfalls of a variable called "cnt")...

Why do we need so many shifts? You need (sizeof int) * CHAR_BITS shifts
even if there are no bits set in i.

At the least, this may be less wasteful... (untested)

int bitcount(unsigned int i) /* don't you want it unsigned? */
{
unsigned int cnt = 0;
while(i) {
cnt += i & 1;
i >>= 1;
}
return cnt;
}

Seems equivalent to (but more verbose than)
http://graphics.stanford.edu/~seande...ntBitsSetNaive

That webpage then looks at other techniques...
Nov 5 '07 #3
Richard <rg****@gmail.comwrote:
"lovecreatesbea...@gmail.com" <lo***************@gmail.comwrites:
int bitcount(int i)
{
unsigned int cnt = 0, MASK;

for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
}

Someone else will tell you about left shifting out of range ( I reckon
its probably fine with an unsigned int)
Where bitwise operations are concerned, never reckon, make sure. They're
nasty, surprising bastards that will bite you sooner or later if you
don't. In this case, though, I'm sure you reckoned correctly.
but I would remove the comparison to MASK
Yes; it's an optimisation that I wouldn't expect even a good optimiser
to get automatically.
and put MASK in lower case since upper case tends to indicate a
constant/#define.
I agree.

Richard
Nov 5 '07 #4
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Richard <rg****@gmail.comwrote:
>"lovecreatesbea...@gmail.com" <lo***************@gmail.comwrites:
int bitcount(int i)
{
unsigned int cnt = 0, MASK;

for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
}

Someone else will tell you about left shifting out of range ( I reckon
its probably fine with an unsigned int)

Where bitwise operations are concerned, never reckon, make sure. They're
nasty, surprising bastards that will bite you sooner or later if you
don't. In this case, though, I'm sure you reckoned correctly.
>but I would remove the comparison to MASK

Yes; it's an optimisation that I wouldn't expect even a good optimiser
to get automatically.
>and put MASK in lower case since upper case tends to indicate a
constant/#define.

I agree.

Richard
Although I did forget to suggest the "reduced bit check" which Mark
correctly diagnosed.
Nov 5 '07 #5
On Nov 5, 11:54 pm, Mark Bluemel <mark_blue...@pobox.comwrote:
lovecreatesbea...@gmail.com wrote:
I read some old posts, they did this task in very different ways. How
is the following one?
/*
* Count the bit set in an integer. eg. integer: 0x01101011, bitcount: 5
*/
int bitcount(int i)
{
unsigned int cnt = 0, MASK;
for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
}

Leaving aside the problems of reading this code aloud (I used to be a
trainer and I know the pitfalls of a variable called "cnt")...

Why do we need so many shifts? You need (sizeof int) * CHAR_BITS shifts
even if there are no bits set in i.

At the least, this may be less wasteful... (untested)
Thank you.

But my version may do less addition operation. Is addition operation
more wasteful than if's?
int bitcount(unsigned int i) /* don't you want it unsigned? */
{
unsigned int cnt = 0;
while(i) {
cnt += i & 1;
i >>= 1;
}
return cnt;
}

Seems equivalent to (but more verbose than)http://graphics.stanford.edu/~seande...ntBitsSetNaive

That webpage then looks at other techniques...
Nov 5 '07 #6
In article <11**********************@i13g2000prf.googlegroups .com>,
lovecreatesbea...@gmail.com <lo***************@gmail.comwrote:
>But my version may do less addition operation. Is addition operation
more wasteful than if's?
It depends not only on the instruction set architecture but also
on the exact processor revision, and it depends upon the surrounding
code.

Historically, 'if' was noticably more expensive than addition,
but processors have become pretty smart to reduce the difference;
some have "move conditional" instructions, some will
internally start working on two "hypothetical" cases simultaneously
of the branch happening or not happening and will discard the
unneeded hypothesis when the condition is fully evaluated
(which is harder than it sounds because it has to hold on to
exceptions, supressing any exceptions that didn't "really" occur
but allowing the exceptions for the hypothetical side that got
realized.)
--
"I was very young in those days, but I was also rather dim."
-- Christopher Priest
Nov 5 '07 #7
lovecreatesbea...@gmail.com wrote:
>
On Nov 5, 11:54 pm, Mark Bluemel <mark_blue...@pobox.comwrote:
lovecreatesbea...@gmail.com wrote:
is the following one?
/*
* Count the bit set in an integer.
eg. integer: 0x01101011, bitcount: 5
*/
int bitcount(int i)
{
unsigned int cnt = 0, MASK;
for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
(i) is the wrong type. It should be unsigned.
If (i) has a value of (-1), then how many bits are set in (i)
depends on which of three representations is used,
but bitcount will always return the number of bits
used by two's complement representation.
cnt++;
return cnt;
}
Leaving aside the problems of reading this code aloud
(I used to be a
trainer and I know the pitfalls of a variable called "cnt")...

Why do we need so many shifts?
You need (sizeof int) * CHAR_BITS shifts
even if there are no bits set in i.

At the least, this may be less wasteful... (untested)

Thank you.

But my version may do less addition operation. Is addition operation
more wasteful than if's?
The last time that I was looking cpu's was in the 1990's.
At that time, typically, a conditional jump
took about twice as long as an integer addition operation.

By every metric I know for guessing how fast a function will be,
bit_count should be faster than bitcount.

unsigned bit_count(unsigned n)
{
unsigned count;

for (count = 0; n != 0; n &= n - 1) {
++count;
}
return count;
}

--
pete
Nov 5 '07 #8
On Nov 5, 9:18 pm, pete <pfil...@mindspring.comwrote:
unsigned bit_count(unsigned n)
{
unsigned count;

for (count = 0; n != 0; n &= n - 1) {
++count;
}
return count;

}
What's much more interesting is a _fast_ implementation of the
following:

/* Return the number of bits set n consecutive ints */
unsigned long array_bitcount (unsigned int* p, unsigned long
number_of_ints)
{
unsigned long count, i;
for (i = 0, count = 0; i < number_of_ints; ++i)
count += bit_count (p [i]);
}
Nov 5 '07 #9
"lovecreatesbea...@gmail.com" <lo***************@gmail.comwrites:
int bitcount(int i)
{
unsigned int cnt = 0, MASK;

for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
}
I have timed the following in the past as being quite fast. It
is branch-free:

/* Compute and return the the number of 1-bits set in X. */
int
count_one_bits_32 (uint32_t x)
{
x = ((x & 0xaaaaaaaaU) >1) + (x & 0x55555555U);
x = ((x & 0xccccccccU) >2) + (x & 0x33333333U);
x = (x >16) + (x & 0xffff);
x = ((x & 0xf0f0) >4) + (x & 0x0f0f);
return (x >8) + (x & 0x00ff);
}

--
"I ran it on my DeathStation 9000 and demons flew out of my nose." --Kaz
Nov 5 '07 #10
On 5 Nov, 15:33, "lovecreatesbea...@gmail.com"
<lovecreatesbea...@gmail.comwrote:
I read some old posts, they did this task in very different ways. How
is the following one?

Thank you for your time.

/
************************************************** ******************************
* Count the bit set in an integer. eg. integer: 0x01101011, bitcount:
5

************************************************** *****************************/

int bitcount(int i)
{
unsigned int cnt = 0, MASK;

for (MASK = 0x1; MASK != 0; MASK <<= 1)
if ((MASK & i) == MASK)
cnt++;
return cnt;
Since others are going for speed how about the following. (The C may
not be completely correct.) It combines fast lookup with a small
table. There is a reasonable chance that the looked up value will be
in cache (which would be better if there were some way to align the
array).

int nibble_bits[] = { /* The number of bits in each nibble 0 to 15 */
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
}

int bitcount (int i) {
int bits_set = 0;

for (; i; i >>= 4) {
bits_set += nibble_bits[i & 0xf];
}
return bits_set;
}
Nov 5 '07 #11
Ben Pfaff wrote:
I have timed the following in the past as being quite fast. It
is branch-free:

/* Compute and return the the number of 1-bits set in X. */
int
count_one_bits_32 (uint32_t x)
{
x = ((x & 0xaaaaaaaaU) >1) + (x & 0x55555555U);
x = ((x & 0xccccccccU) >2) + (x & 0x33333333U);
x = (x >16) + (x & 0xffff);
x = ((x & 0xf0f0) >4) + (x & 0x0f0f);
return (x >8) + (x & 0x00ff);
}
Just for kicks, here's yet another size-specific (and also
generalizable) version. Here multiplication does bit tallying in pruned
bitmaps.
Whether it's better or worse probably depends on the instruction set.
#define ONES 0x11111111U
unsigned mybits(uint32_t x)
{
unsigned count;
count = ((x & ONES) * ONES) >28;
count += (((x>>1) & ONES) * ONES) >28;
count += (((x>>2) & ONES) * ONES) >28;
count += (((x>>3) & ONES) * ONES) >28;
return count;
}

--
Ark
Nov 6 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
by: Joseph Shraibman | last post by:
On a 7.3.4 database: explain analyse select count(*) from elog; Aggregate (cost=223764.05..223764.05 rows=1 width=0) (actual time=81372.11..81372.11 rows=1 loops=1) -> Seq Scan on elog ...
3
by: jason | last post by:
Hello. I've got this simple collection populate code I downloaded from the net (sorry can't find source now) I'm trying to test, but I can't seem to get it to work. Any help would be greatly...
10
by: Jon | last post by:
I want to count the number of instances of a certain string(delimiter) in another string. I didn't see a function to do this in the framework (if there is, please point me to it). If not, could...
6
by: Tejpal Garhwal | last post by:
I have datagrid filled with some data rows. At the run time i want know how many total rows are there in the data grid ? Any idea ? Any Suggestions ? Thanks in advance Tej
61
by: John Baker | last post by:
When declaring an integer, you can specify the size by using int16, int32, or int64, with plain integer being int32. Is integer the accepted default in the programming community? If so, is...
13
by: coinjo | last post by:
Is there any function to determine the length of an integer string?
7
by: eliben | last post by:
Hello, I'm interested in converting integers to a binary representation, string. I.e. a desired function would produce: dec2bin(13) ="1101" The other way is easily done in Python with the...
4
by: =?Utf-8?B?a2s=?= | last post by:
Personally I do not like the "sophisticated" code but, anyway I have this (I squeez it to save a space): using System; using System.Collections.Generic; public class SamplesArray { public...
1
by: monkey0525 | last post by:
As the title of the question states, my program is not able to store an integer from a seperate text file provided. For instance, instead of printing the desired output: "$45.00 17 2222 Chuck...
0
by: bbaamm | last post by:
Imports System.Data Imports System.Data.SqlClient Imports System.Data.OracleClient Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Globalization...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.