473,412 Members | 5,714 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,412 software developers and data experts.

number of 1's in an integer

Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?
Note: no looping is allowed.

i agree this is a homework question. i tried a lot
but couldn't find any solution.
Any hints will be highly appreciated.

thanx a ton...
Nov 14 '05 #1
10 5893
junky_fellow wrote:
Can anybody suggest me an efficient way of [...]


What is your definition of efficient?

Small execution time? Small code size? Small data size? Easy to read?

BTW, there is no need to assume how many bits there are in an int, you
can use sizeof(unsigned int) * CHAR_BIT

Nov 14 '05 #2

"junky_fellow" <ju**********@yahoo.co.in> wrote in message
news:8c**************************@posting.google.c om...
Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?
Note: no looping is allowed.

i agree this is a homework question. i tried a lot
but couldn't find any solution.
Any hints will be highly appreciated.

thanx a ton...


Create a lookup table with 256 entries where each entry holds the number of
bits for each byte value (from 0 - 255):

/* Notice the recursive series pattern... */
/* Check out the first four entries, then every other entry, then every
fourth entry (see the pattern.?.) */
/* Another solution could make use of this pattern....!!! */
int bits_in_a_byte[256]={0,1,1,2, 1,2,2,3, 1,2,2,3, 2,3,3,4, 1,2,2,3 ,
2,3,3,4, 2,3,3,4, 3,4,4,5.etc..};

The for each byte in you 4 byte int you can do a lookup on this table and
add all the results together.

You can use casting of pointers to get each byte of the int as follows:

long value;
char byte1, byte2, byte3, byte4;
char *p;

p=(char *) &value;
byte1= p[0];
byte2=p[1];
byte3=p[2];
byte4=p[3];

This makes some assumptions about the sizeof long etc but I hope you get the
general gist...

Sean


Nov 14 '05 #3


junky_fellow wrote:
Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?
Note: no looping is allowed.

i agree this is a homework question. i tried a lot
but couldn't find any solution.
Any hints will be highly appreciated.

thanx a ton...


Since you say it's a homework question I won't give you the code
but suggest you use recursion to work around the looping bit. And
take care when you are going to shift your integer number: shifting
right signed ints is implementation defined. But if you get it right,
you don't even need to know (not to mention assume) the size of
your ints.

--
ir. H.J.H.N. Kenter ^^
Electronic Design & Tools oo ) Philips Research Labs
Building WAY 3.23 =x= \ ar**********@philips.com
Prof. Holstlaan 4 (WAY31) | \ tel. +31 40 27 45334
5656 AA Eindhoven /|__ \ tfx. +31 40 27 44626
The Netherlands (____)_/ http://www.kenter.demon.nl/

Famous last words: Segmentation Fault (core dumped)

Nov 14 '05 #4
Sean Kenwrick wrote:
junky_fellow wrote:
Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?
Note: no looping is allowed.


Create a lookup table with 256 entries where each entry holds
the number of bits for each byte value (from 0 - 255):


What if CHAR_BIT > 8 ?

<g>

Nov 14 '05 #5
In article <8c**************************@posting.google.com >,
ju**********@yahoo.co.in (junky_fellow) wrote:
Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?


Two favorites:

int bitcount1 (unsigned long x)
{
int n = 0;
if (x) do ++n; while (x &= x-1);
return n;
}

/* assume unsigned long is 32 bits */
int bitcount2 (unsigned long x)
{
x -= ((x>>1)&013333333333)+((x>>2)&01111111111);
x = ((x>>3)+x)&030707070707;
x += x>>18;
return ((x>>12)+(x>>6)+x)&63;
}
François Grieu
Nov 14 '05 #6

"Grumble" <in*****@kma.eu.org> wrote in message
news:c0**********@news-rocq.inria.fr...
Sean Kenwrick wrote:
junky_fellow wrote:
Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?
Note: no looping is allowed.


Create a lookup table with 256 entries where each entry holds
the number of bits for each byte value (from 0 - 255):


What if CHAR_BIT > 8 ?

<g>


I did state in my original post that I made some assumptions and that this
was really just a concept for which the OP to build upon....

Sean
Nov 14 '05 #7
junky_fellow wrote:

Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?
Note: no looping is allowed.

i agree this is a homework question. i tried a lot
but couldn't find any solution.


The integer N contains (1 + 1 + 1 + .... 1) == N ones. If this is
not what you want the problem is poorly stated, and you might with
to look at M Grieus posting.

Even if the actual meaning is "1 bits", the problem without
looping is foolish. Any solution requires further system
knowledge, such as CHAR_BIT. Also there is no need to assume
sizeof(int) == 4.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #8
"Grumble" <in*****@kma.eu.org> wrote in message
news:c0**********@news-rocq.inria.fr...
junky_fellow wrote:
Can anybody suggest me an efficient way of [...]


What is your definition of efficient?

Small execution time? Small code size? Small data size? Easy to read?

BTW, there is no need to assume how many bits there are in an int, you
can use sizeof(unsigned int) * CHAR_BIT


This is useful as an upper bound only. It is not guaranteed to be number of
sign and value bits in an int.

--
Peter
Nov 14 '05 #9
Francois Grieu <fg****@micronet.fr> wrote in message news:<fg**************************@news.cis.dfn.de >...
In article <8c**************************@posting.google.com >,
ju**********@yahoo.co.in (junky_fellow) wrote:
Can anybody suggest me an efficient way of counting
no. of 1's in an integer (assume size of int=4)?


Two favorites:

int bitcount1 (unsigned long x)
{
int n = 0;
if (x) do ++n; while (x &= x-1);
return n;
}

/* assume unsigned long is 32 bits */
int bitcount2 (unsigned long x)
{
x -= ((x>>1)&013333333333)+((x>>2)&01111111111);
x = ((x>>3)+x)&030707070707;
x += x>>18;
return ((x>>12)+(x>>6)+x)&63;
}
François Grieu


thanx a lot. The first one is really appreciable. However,the
logic of second one is still not clear.
Nov 14 '05 #10
On 9 Feb 2004 05:17:20 -0800, in comp.lang.c , ju**********@yahoo.co.in
(junky_fellow) wrote:
Francois Grieu <fg****@micronet.fr> wrote in message news:<fg**************************@news.cis.dfn.de >...
In article <8c**************************@posting.google.com >,
ju**********@yahoo.co.in (junky_fellow) wrote:

/* assume unsigned long is 32 bits */
int bitcount2 (unsigned long x)
{
x -= ((x>>1)&013333333333)+((x>>2)&01111111111);
x = ((x>>3)+x)&030707070707;
x += x>>18;
return ((x>>12)+(x>>6)+x)&63;
}
François Grieu


thanx a lot. The first one is really appreciable. However,the
logic of second one is still not clear.


rewrite the magic numbers in binary form, work through it for a couple of
numbers (also in binary form), and it will become clear.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #11

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

Similar topics

21
by: Gavin | last post by:
Hi, I'm a newbie to programming of any kind. I have posted this to other groups in a hope to get a response from anyone. Can any one tell me how to make my VB program read the Bios serial number...
2
by: sarmin kho | last post by:
Hi Pythoners, When it is an integer number, what is the range of the integer number and long integer number?? do we have typecasting of 8bits or 16bits signed and unsigned number in python? ...
27
by: Gaijinco | last post by:
Sooner or later everytime I found recreational programming challenges I stumble with how I test if a number is has decimal places differnt than 0? For example if I want to know if a number is a...
7
by: Egor Shipovalov | last post by:
I'm implementing paging through search results using cursors. Is there a better way to know total number of rows under a cursor than running a separate COUNT(*) query? I think PostgreSQL is bound...
7
by: Shuffs | last post by:
Could someone, anyone please tell me what I need to amend, to get this function to take Sunday as the first day of the week? I amended the Weekday parts to vbSunday (in my code, not the code...
6
by: Penguin | last post by:
At some long ago time Steve Jorgensen answered thus: Subject: Re: How can I round a time? Newsgroups: comp.databases.ms-access Date: 1998/12/11 Access represents a date internally as a double...
10
by: chanma | last post by:
code1:var x=0xf0000000; alert(x); output:4026531840 code2:var b=0xf<<28; alert(b); output:-268435456
2
by: Alex Buell | last post by:
Is there an elegant way of converting strings containing digits between different number bases in C++? I.e.: 10 (base 2) = 2 (base 10) FF (base 16) = 256 (base 10) F (base 16) = 1111 (base 2)...
4
by: SweetLeftFoot | last post by:
Hello, i have designed some code that works out the first 250 prime numbers and prints them to the screen. However i need to implement 2 functions, one of which returns a 1 if the number is a prime...
1
by: Smalley | last post by:
Need some help please. Have this code and for some reason it is not working correctly. I am not receiving errors, just the table is not being populated at all. I have created the tbl and the frm...
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: 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
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,...
0
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...
0
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...
0
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,...
0
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...

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.