473,766 Members | 2,093 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6529
"lovecreatesbea ...@gmail.com" <lo************ ***@gmail.comwr ites:
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(unsign ed 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.c omwrote:
"lovecreatesbea ...@gmail.com" <lo************ ***@gmail.comwr ites:
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.c omwrote:
>"lovecreatesbe a...@gmail.com" <lo************ ***@gmail.comwr ites:
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...@p obox.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(unsign ed 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************ **********@i13g 2000prf.googleg roups.com>,
lovecreatesbea. ..@gmail.com <lo************ ***@gmail.comwr ote:
>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 "hypothetic al" 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...@p obox.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(unsig ned 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...@mindsp ring.comwrote:
unsigned bit_count(unsig ned 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.comwr ites:
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

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

Similar topics

22
3214
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 (cost=0.00..203012.24 rows=8300724 width=0) (actual time=3.91..71542.53 rows=8313762 loops=1) Total runtime: 81378.42 msec
3
4586
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 appreciated. I've compiled the following VB.NET into a DLL: Imports System Imports System.Data Imports System.Data.SqlClient Imports System.Collections
10
2861
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 someone let me know if the method I've used below is efficient or if there is a better way to do it, as these will be rather large strings I'm searching in. Thanks Public Shared Function CountDelimiter(ByVal strInput As String, ByVal...
6
6704
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
3388
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 there a way to remove the ones with size predefined from the autolisting of types when I am declaring something? -- To Email Me, ROT13 My Shown Email Address
13
3654
by: coinjo | last post by:
Is there any function to determine the length of an integer string?
7
2915
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 int() function. Perl has a very efficient way to do dec2bin, because its pack/unpack
4
2328
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 static void Main() {
1
1992
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 Taylor All Star" It prints: "$45.00 17 0 Chuck Taylor All Star" So even though I provided the price (double), quantity (integer) and name (string), my program can store all of it except for the blasted ID number (integer). If anyone is...
0
1952
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 Partial Class plaza_dailyDeclareExcessShort Inherits System.Web.UI.Page Private Report1 As ReportDocument Private OraCon2 As New OracleConnection(ConfigurationManager.AppSettings("OraCon2"))
0
9404
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10168
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10008
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9837
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7381
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.