473,890 Members | 1,430 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How many bits are '1' in a integer variable?

Hi folks,

I am trying to find a more efficient way to count "How many bits are
'1' in a integer variable?".

I still have no idea to count the bits except using a loop and "if"
statements.
Could you know any other more efficient way?

Cuthbert

int main (void)
{
int var = 0xFF0F;
int i, count = 0;
int mask = 1;
for ( i = 0; i < sizeof(int)*8 ; i++ )
if ( mask<<i & var) count++ ;

printf("%d\n", count);

return 0;
}

Sep 12 '06 #1
34 11350
Cuthbert wrote:
Hi folks,

I am trying to find a more efficient way to count "How many bits are
'1' in a integer variable?".

I still have no idea to count the bits except using a loop and "if"
statements.
Could you know any other more efficient way?
Break the int into bytes and use a lookup table.

--
Thomas M. Sommers -- tm*@nj.net -- AB2SB

Sep 12 '06 #2
T.M. Sommers posted:
Cuthbert wrote:
>Hi folks,

I am trying to find a more efficient way to count "How many bits are
'1' in a integer variable?".

I still have no idea to count the bits except using a loop and "if"
statements.
Could you know any other more efficient way?

Break the int into bytes and use a lookup table.

I'm sure there's a better way than that... perhaps even an expression
yielding a compile-time constant. Maybe something like:
#define UINT_BITS_SET(x )\
!!((x)&1U) + !!((x)&1U<<1) + !!((x)&1U<<2) + !!((x)&1U<<3)\
+ !!((x)&1U<<4) + !!((x)&1U<<5) + !!((x)&1U<<6) + !!((x)&1U<<7)\
+ !!((x)&1U<<8) + !!((x)&1U<<9) + !!((x)&1U<<10) + !!((x)&1U<<11)\
+ !!((x)&1U<<12) + !!((x)&1U<<13) + !!((x)&1U<<14) + !!((x)&1U<<15)\
+ !!((x)&1U<<16) + !!((x)&1U<<17) + !!((x)&1U<<18) + !!((x)&1U<<19)\
+ !!((x)&1U<<20)

I'm not sure if it's undefined behaviour to left shift an unsigned int by
more places than it has bits; if not, then you can simply go as high as you
want:

+ !!((x)&1U<<6354 8)

If it is however, then you could use the IMAX_BITS macro in conjunction
with the modulus and division operators to keep things safe.

--

Frederick Gotham
Sep 12 '06 #3

Cuthbert wrote:
Hi folks,
a bit simpler and therefore perhaps somewhat faster:

int main (void)
{
int var = 0xFF0F;
int i, count = 0;

for ( i = 0; i < sizeof(int)*8 ; i++ )
{ count += var & 1; var >>= 1; }

printf("%d\n", count);

return 0;
}

a byte lookup table might or might not be faster, depending on what
happens with the cache.

Sep 12 '06 #4
In article <11************ **********@d34g 2000cwd.googleg roups.com>,
Ancient_Hacker <gr**@comcast.n etwrote:
>Cuthbert wrote:
>Hi folks,
Please quote enough context so that people know what is being discussed.
In this case it is counting the number of 1 bits in an integer variable.
>a bit simpler and therefore perhaps somewhat faster:
>int main (void)
{
int var = 0xFF0F;
int i, count = 0;
for ( i = 0; i < sizeof(int)*8 ; i++ )
{ count += var & 1; var >>= 1; }
printf("%d\n", count);

return 0;
}
Why sizeof(int)*8 ?

It appears to me that you have assumed CHAR_BIT to be 8.
--
"law -- it's a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)
Sep 12 '06 #5
Ancient_Hacker wrote:
a byte lookup table might or might not be faster, depending on what
happens with the cache.
My favorite approach that I've seen to this (Homework) problem involved
a combination of table lookup (for all the 4-bit unch ofcombinations)
and a series of shifts.

Pretty good compromise.

Here are a few different ways to do it.
http://graphics.stanford.edu/~seande...ntBitsSetNaive
Sep 12 '06 #6
Frederick Gotham said:
T.M. Sommers posted:
>Cuthbert wrote:
>>Hi folks,

I am trying to find a more efficient way to count "How many bits are
'1' in a integer variable?".

I still have no idea to count the bits except using a loop and "if"
statements.
Could you know any other more efficient way?

Break the int into bytes and use a lookup table.


I'm sure there's a better way than that... perhaps even an expression
yielding a compile-time constant. Maybe something like:
#define UINT_BITS_SET(x )\
!!((x)&1U) + !!((x)&1U<<1) + !!((x)&1U<<2) + !!((x)&1U<<3)\
+ !!((x)&1U<<4) + !!((x)&1U<<5) + !!((x)&1U<<6) + !!((x)&1U<<7)\
+ !!((x)&1U<<8) + !!((x)&1U<<9) + !!((x)&1U<<10) + !!((x)&1U<<11)\
+ !!((x)&1U<<12) + !!((x)&1U<<13) + !!((x)&1U<<14) + !!((x)&1U<<15)\
+ !!((x)&1U<<16) + !!((x)&1U<<17) + !!((x)&1U<<18) + !!((x)&1U<<19)\
+ !!((x)&1U<<20)
I'm not convinced that's a better way than:

unsigned int count_set_bits( unsigned long n)
{
unsigned int set_bits[] =
{
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4
};
unsigned int count = 0;
while(n 0)
{
count += set_bits[n & 0xf];
n >>= 4;
}
return count;
}

Your solution doesn't appear to cope with integers wider than 21 bits, for a
start. Secondly, it doesn't cope with integers that are /fewer/ than 21
bits wide! Thirdly, it could conceivably be counting "padding bits", bits
that do not contribute to the value of the integer.
I'm not sure if it's undefined behaviour to left shift an unsigned int by
more places than it has bits; if not, then you can simply go as high as
you want:
Quoth 3.3.7 of C90: "The integral promotions are performed on each of the
operands. The type of the result is that of the promoted left operand. If
the value of the right operand is negative or is greater than or equal to
the width in bits of the promoted left operand, the behavior is undefined."

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 12 '06 #7
Cuthbert wrote:
Hi folks,

I am trying to find a more efficient way to count "How many bits are
'1' in a integer variable?".
http://graphics.stanford.edu/~seander/bithacks.html

Pay close attention, though; most of these hacks assume integer sizes, two's
complement machines, or other things that may be quite justifiable, but
nevertheless render the code unportable.

S.
Sep 12 '06 #8
Skarmander wrote:
Cuthbert wrote:
>Hi folks,

I am trying to find a more efficient way to count "How many bits are
'1' in a integer variable?".
http://graphics.stanford.edu/~seander/bithacks.html

Pay close attention, though; most of these hacks assume integer sizes,
two's complement machines, or other things that may be quite
justifiable, but nevertheless render the code unportable.

S.
I believe many of these hacks are in "Hacker's Delight" by
Henry Warren. As is the answer to the OP's question.

--
Julian V. Noble
Professor Emeritus of Physics
University of Virginia
Sep 12 '06 #9
Cuthbert wrote:
>
Hi folks,

I am trying to find a more efficient way to count "How many bits are
'1' in a integer variable?".

I still have no idea to count the bits except using a loop and "if"
statements.
Could you know any other more efficient way?

Cuthbert

int main (void)
{
int var = 0xFF0F;
int i, count = 0;
int mask = 1;
for ( i = 0; i < sizeof(int)*8 ; i++ )
if ( mask<<i & var) count++ ;

printf("%d\n", count);

return 0;
}
/* BEGIN new.c */

#include <stdio.h>

unsigned bit_count(unsig ned n);

int main (void)
{
unsigned var = 0xFF0F;
unsigned count = bit_count(var);

printf("%u\n", count);
return 0;
}

unsigned bit_count(unsig ned n)
{
unsigned count;

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

/* END new.c */
--
pete
Sep 12 '06 #10

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

Similar topics

10
2795
by: Danny Anderson | last post by:
Hola! I have an array of shorts that represents a stream of data. This data is packed in tight, so certain elements may actually contain data for more than one variable. I am to decipher this stream. The first variable packed into this array happens to be a short, meaning I get away with a simple assignment: myFirstVariable=myArray;
6
3501
by: cylin | last post by:
Hi all, If I have a variable and it's just have 22 bits, and I must set this variable unsigned integer. This 2's complement value maybe is negative. For example: A= 11 1111 1111 1110 1100 0000 = 4193984 3 f f e c 0 A's 2's complement should be
9
8793
by: GGG | last post by:
Noticed something odd in the way bit shifting was working today. As far as I have ever heard, shifting will shift in zeros(signed ints aside) However I foudn something odd when I am shifting exactly the number of bits in a value... i.e. uint32_t x = 5;
26
8258
by: G Patel | last post by:
Hi, I'm wondering if anyone knows if the following function will function properly as a set-bit counter on non 2s complement machines (as K&R2 implies). | int bitcount(unsigned x) | { | int count; | | for(count = 0; x != 0; count++, x &= (x-1)) | ;
14
2603
by: vib | last post by:
Hi there, union UC32 { unsigned int L; unsigned short S; unsigned char C; } UC32; with the above structure, I am able to shift bits of C, into C, and C into C so on and so forth till C as they are "union"ed
36
5342
by: Digital Puer | last post by:
Hi, suppose I have an unsigned long long. I would like to extract the front 'n' bits of this value and convert them into an integer. For example, if I extract the first 3 bits, I would get an int between 0 and 7 (=2^3-1). Could someone please help out? I can assume the largest returned value fits in an int. Also, I'm on a big-endian PPC (AIX), in case that matters. Ideally, I'd like to implement a prototype like: int...
64
3971
by: yossi.kreinin | last post by:
Hi! There is a system where 0x0 is a valid address, but 0xffffffff isn't. How can null pointers be treated by a compiler (besides the typical "solution" of still using 0x0 for "null")? - AFAIK C allows "null pointers" to be represented differently then "all bits 0". Is this correct? - AFAIK I can't `#define NULL 0x10000' since `void* p=0;' should work just like `void* p=NULL'. Is this correct?
40
36524
by: KG | last post by:
Could any one tell me how to reverse the bits in an interger?
6
2854
by: John Messenger | last post by:
I notice that the C standard allows padding bits in both unsigned and signed integer types. Does anyone know of any real-world examples of compilers that use padding bits? -- John
0
9979
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9826
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
11234
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...
1
10925
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9640
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
8018
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
7171
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5854
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4276
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.