473,378 Members | 1,372 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,378 software developers and data experts.

How to count bits in a unsigned int?

On 32-bit platform,
I am working on getting how many bits equal to 1 without an if loop.

--
Regards.
Terrence Feldman
Email: tf********@gmail.com

Feb 16 '07 #1
19 16252
tf********@gmail.com wrote:
On 32-bit platform,
I am working on getting how many bits equal to 1 without an if loop.
Use a for loop or a while loop, testing each bit until you have no
more bits to test. I'm not sure what an if loop would be like, unless
you're using goto.

Feb 16 '07 #2
tf********@gmail.com writes:
On 32-bit platform,
I am working on getting how many bits equal to 1 without an if loop.
Your task is made easier by the fact that there's no such thing as an
"if loop", so you won't have any trouble avoiding it.

The most important step in solving any problem is defining exactly
what the problem is. You haven't done that.

But questions of the form "How can I do X without using feature Y?"
are almost always homework assignments. We won't do your homework for
you (unless you're willing to pay our exhorbitant consulting fees
*and* let us submit our solutions directly to your instructor).

We're quite willing to help you solve any problems in your C code, but
we can't do that unless you write some and post it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 16 '07 #3

<tf********@gmail.comwrote in message n
On 32-bit platform,
I am working on getting how many bits equal to 1 without an if loop.
On the lowest bit can equal one. The rest equal 2, 4, 8 ... etc.

So if (x & 1) is your answer.

Tell your professor he means the number of set bits.
Feb 16 '07 #4
Harald van D?k wrote:
tf********@gmail.com wrote:
>On 32-bit platform, I am working on getting how many bits equal
to 1 without an if loop.

Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.
I have no idea what an 'if loop' is.

unsigned int value, count;

value = whatever;
count = 0;

/* loop invariant: count + bitsinvalue = bitsinwhatever */
while (value) {
count++;
value = (value - 1) & value;
}
/* bitsinvalue = 0 */

which doesn't care how wide an int is.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 16 '07 #5
CBFalconer wrote:
Harald van D?k wrote:
tf********@gmail.com wrote:
On 32-bit platform, I am working on getting how many bits equal
to 1 without an if loop.
Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.

I have no idea what an 'if loop' is.
[example]
which doesn't care how wide an int is.
And the way I mentioned does?

count = value < 0;
for (bit = 1; bit < INT_MAX / 2; bit *= 2)
if (value & bit)
count++;

It accepts ints of any width.

Feb 16 '07 #6
Harald van Dijk wrote:
CBFalconer wrote:
Harald van D?k wrote:
tf********@gmail.com wrote:
>
>On 32-bit platform, I am working on getting how many bits equal
>to 1 without an if loop.
>
Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.
I have no idea what an 'if loop' is.
[example]
which doesn't care how wide an int is.

And the way I mentioned does?

count = value < 0;
count = 0;
for (bit = 1; bit < INT_MAX / 2; bit *= 2)
for (bit = 1; bit != 0; bit *= 2)
if (value & bit)
count++;

It accepts ints of any width.
The question asked for unsigned ints, but I posted an example for ints.

Feb 16 '07 #7
Harald van Dijk wrote:
Harald van Dijk wrote:
CBFalconer wrote:
Harald van D?k wrote:
tf********@gmail.com wrote:

On 32-bit platform, I am working on getting how many bits equal
to 1 without an if loop.

Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.
>
I have no idea what an 'if loop' is.
[example]
which doesn't care how wide an int is.
And the way I mentioned does?

count = value < 0;

count = 0;
for (bit = 1; bit < INT_MAX / 2; bit *= 2)

for (bit = 1; bit != 0; bit *= 2)
if (value & bit)
count++;

It accepts ints of any width.

The question asked for unsigned ints, but I posted an example for ints.
Sorry for replying to myself so much, but the example for ints was
wrong anyway. After the loop exited, I needed to check value & bit
once more, to see if the highest value bit was set.

Feb 16 '07 #8
static inline ulong bit_count(ulong x) {
// Return number of bits set
x = (0x55555555 & x) + (0x55555555 & (x>1)); // 0-2 in 2 bits
x = (0x33333333 & x) + (0x33333333 & (x>2)); // 0-4 in 4 bits
x = (0x0f0f0f0f & x) + (0x0f0f0f0f & (x>4)); // 0-8 in 8 bits
x = (0x00ff00ff & x) + (0x00ff00ff & (x>8)); // 0-16 in 16
bits
x = (0x0000ffff & x) + (0x0000ffff & (x>>16)); // 0-31 in 32
bits
return x;
}

//Algorithms for programmers ideas and source code
//by J¨org Arndt, ar***@jjj.de

Feb 16 '07 #9
CoL
You also try recursion for the same....

~col

On Feb 16, 3:03Â*pm, "Harald van Dijk" <true...@gmail.comwrote:
CBFalconer wrote:
Harald van D?k wrote:
tfeldma...@gmail.com wrote:
>On 32-bit platform, I am working on getting how many bits equal
>to 1 without an if loop.
Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.
I have no idea what an 'if loop' is.
[example]
which doesn't care how wide an int is.

And the way I mentioned does?

count = value < 0;
for (bit = 1; bit < INT_MAX / 2; bit *= 2)
Â* Â* if (value & bit)
Â* Â* Â* Â* count++;

It accepts ints of any width.

Feb 16 '07 #10
CoL wrote:
You also try recursion for the same....

~col
To count bits? You're not in the business of performance eh?
Feb 16 '07 #11
Harald van D?k wrote:
>
CBFalconer wrote:
Harald van D?k wrote:
tf********@gmail.com wrote:
>
>On 32-bit platform, I am working on getting how many bits equal
>to 1 without an if loop.
>
Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.
I have no idea what an 'if loop' is.
[example]
which doesn't care how wide an int is.

And the way I mentioned does?

count = value < 0;
for (bit = 1; bit < INT_MAX / 2; bit *= 2)
if (value & bit)
count++;

It accepts ints of any width.
But it needs to know the precise type. My version will work when
fed bytes, longs, shorts, etc. (with matching changes in the type
of value, but making value an unsigned long will cover them all,
except long long which may or may not be available).

I find code fragments that need no editing more useful.
--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 16 '07 #12
CBFalconer wrote:
But it needs to know the precise type. My version will work when
fed bytes, longs, shorts, etc. (with matching changes in the type
of value, but making value an unsigned long will cover them all,
except long long which may or may not be available).

I find code fragments that need no editing more useful.
What's wrong with the typical straightforward way?

int bs(unsigned long v)
{
int c;

for (c = 0; v; v >>= 1)
c += v & 1;

return c;
}
Feb 16 '07 #13
CBFalconer wrote:
Harald van D?k wrote:

CBFalconer wrote:
Harald van D?k wrote:
tf********@gmail.com wrote:

On 32-bit platform, I am working on getting how many bits equal
to 1 without an if loop.

Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.
>
I have no idea what an 'if loop' is.
[example]
which doesn't care how wide an int is.
And the way I mentioned does?

count = value < 0;
for (bit = 1; bit < INT_MAX / 2; bit *= 2)
if (value & bit)
count++;

It accepts ints of any width.

But it needs to know the precise type. My version will work when
fed bytes, longs, shorts, etc. (with matching changes in the type
of value, but making value an unsigned long will cover them all,
except long long which may or may not be available).

I find code fragments that need no editing more useful.
Your version will not work with signed types, and the version for
unsigned types I posted later does not need editing either, as long as
the type of 'bit' is large enough.

Feb 16 '07 #14
Christopher Layne wrote:
CBFalconer wrote:
>But it needs to know the precise type. My version will work when
fed bytes, longs, shorts, etc. (with matching changes in the type
of value, but making value an unsigned long will cover them all,
except long long which may or may not be available).

I find code fragments that need no editing more useful.

What's wrong with the typical straightforward way?

int bs(unsigned long v)
{
int c;

for (c = 0; v; v >>= 1)
c += v & 1;
return c;
}
Nothing that I can see. It will take more cycles, for each 0 bit
to the right of any 1 bit.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 16 '07 #15
tf********@gmail.com wrote:
>
On 32-bit platform,
I am working on getting how many bits equal to 1 without an if loop.
unsigned bit_count(unsigned n)
{
unsigned count;

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

--
pete
Feb 16 '07 #17
jxh
On Feb 16, 5:01 am, Christopher Layne <cla...@com.anodizedwrote:
CoL wrote:
You also try recursion for the same....
~col

To count bits? You're not in the business of performance eh?
Should perform just as well with proper optimizations:

static int
bits_r (unsigned int u, int count)
{
return !u ? count : bits_r(u & u-1, count+1);
}

int
bits (unsigned int u)
{
return bits_r(u, 0);
}

-- James

Feb 17 '07 #18

CBFalconer wrote:
Harald van D?k wrote:
tf********@gmail.com wrote:
On 32-bit platform, I am working on getting how many bits equal
to 1 without an if loop.
Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.

I have no idea what an 'if loop' is.

unsigned int value, count;

value = whatever;
count = 0;

/* loop invariant: count + bitsinvalue = bitsinwhatever */
while (value) {
count++;
value = (value - 1) & value;
}
/* bitsinvalue = 0 */

which doesn't care how wide an int is.
this is an interview question.

i = 0;
while(var)
{
var &= ~(-var);
i++;
}

Feb 17 '07 #19
dick wrote:
CBFalconer wrote:
>Harald van D?k wrote:
>>tf********@gmail.com wrote:

On 32-bit platform, I am working on getting how many bits equal
to 1 without an if loop.

Use a for loop or a while loop, testing each bit until you have
no more bits to test. I'm not sure what an if loop would be like,
unless you're using goto.

I have no idea what an 'if loop' is.

unsigned int value, count;

value = whatever;
count = 0;

/* loop invariant: count + bitsinvalue = bitsinwhatever */
while (value) {
count++;
value = (value - 1) & value;
}
/* bitsinvalue = 0 */

which doesn't care how wide an int is.

this is an interview question.

i = 0;
while(var)
{
var &= ~(-var);
i++;
}
Doesn't work. Consider overflow (-var, for var == INT_MIN, 2'
complement), sign-magnitude representation, 1's complement
representation.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
<http://www.securityfocus.com/columnists/423>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 17 '07 #20

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

Similar topics

26
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) | { | ...
36
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...
11
by: Mockey Chen | last post by:
On 32-bit platform, give you a unsigned int? what is the best way to get how many bits equal to 1. please do not use loop if possible? Thanks in advance. -- Regards. Mockey Chen Email:...
7
by: Matt Kowalczyk | last post by:
Hello, I am working on a compression project and I want to write ASCII characters using the minimum amount of bits. Since I will be writing ASCII characters from 0-127 I only need 7 bits to...
12
by: Frederick Gotham | last post by:
Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant representing the amount of value representation bits in an unsigned integer type. In true C fashion, here it is as a macro:...
40
by: KG | last post by:
Could any one tell me how to reverse the bits in an interger?
11
by: Mack | last post by:
Hi all, I want to write a program to count number of bits set in a number. The condition is we should not loop through each bit to find whether its set or not. Thanks in advance, -Mukesh
77
by: borophyll | last post by:
As I read it, C99 states that a byte is an: "addressable unit of data storage large enough to hold any member of the basic character set of the execution environment" (3.6) and that a byte...
11
by: lovecreatesbea... | last post by:
I read some old posts, they did this task in very different ways. How is the following one? Thank you for your time. /...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: 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:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...

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.