473,659 Members | 3,082 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Logic behind the program

Hello,
the code below calculate the number of bits set in an unsigned
integer.
Can you explain me the logic behind the code?

unsigned int x = Some number;

x=(0xaaaaaaaa&x )>>1+(0x5555555 5&x);
x=(0xcccccccc&x )>>2+(0x3333333 3&x);
x=(0xf0f0f0f0&x )>>4+(0x0f0f0f0 f&x);
x=(0xff00ff00&x )>>8+(0x00ff00f f&x);
x=x>>16+(0x0000 ffff&x));

Aug 29 '07 #1
4 1998
In article <11************ ********@e9g200 0prf.googlegrou ps.com>,
ravi <dc**********@g mail.comwrote:
>the code below calculate the number of bits set in an unsigned
integer.
Can you explain me the logic behind the code?
>unsigned int x = Some number;
>x=(0xaaaaaaaa& x)>>1+(0x555555 55&x);
x=(0xcccccccc& x)>>2+(0x333333 33&x);
x=(0xf0f0f0f0& x)>>4+(0x0f0f0f 0f&x);
x=(0xff00ff00& x)>>8+(0x00ff00 ff&x);
x=x>>16+(0x000 0ffff&x));
That code has floated around a long time, and you could
probably find an explanation for it in the archives.

But you are incorrect that it calculates the number of
bits set in an unsigned integer. It only calculates
the number of bits set in 32 bit unsigned integers.
If your unsigned integers are wider than that, it will
not work.

--
Prototypes are supertypes of their clones. -- maplesoft
Aug 29 '07 #2
On Wed, 29 Aug 2007 15:40:33 +0000 (UTC), ro******@ibd.nr c-cnrc.gc.ca
(Walter Roberson) wrote in comp.lang.c:
In article <11************ ********@e9g200 0prf.googlegrou ps.com>,
ravi <dc**********@g mail.comwrote:
the code below calculate the number of bits set in an unsigned
integer.
Can you explain me the logic behind the code?
unsigned int x = Some number;
x=(0xaaaaaaaa&x )>>1+(0x5555555 5&x);
x=(0xcccccccc&x )>>2+(0x3333333 3&x);
x=(0xf0f0f0f0&x )>>4+(0x0f0f0f0 f&x);
x=(0xff00ff00&x )>>8+(0x00ff00f f&x);
x=x>>16+(0x0000 ffff&x));

That code has floated around a long time, and you could
probably find an explanation for it in the archives.

But you are incorrect that it calculates the number of
bits set in an unsigned integer. It only calculates
the number of bits set in 32 bit unsigned integers.
If your unsigned integers are wider than that, it will
not work.
Platforms with unsigned ints wider than 32 bits are rare but do exist.

On the other hand, platforms with unsigned int narrower than 32 bits
are still very common, although not on the desktop.

On a platform with 24-bit (un)signed ints, and there have been some,
it will produce the correct result.

On a platform with 16-bit (un)signed ints, the code invokes undefined
behavior.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
Aug 30 '07 #3
ravi wrote:
Hello,
the code below calculate the number of bits set in an unsigned
integer.
Can you explain me the logic behind the code?

unsigned int x = Some number;

x=(0xaaaaaaaa&x )>>1+(0x5555555 5&x);
x=(0xcccccccc&x )>>2+(0x3333333 3&x);
x=(0xf0f0f0f0&x )>>4+(0x0f0f0f0 f&x);
x=(0xff00ff00&x )>>8+(0x00ff00f f&x);
x=x>>16+(0x0000 ffff&x));
The easiest way to understand it may be to draw
a picture. (Warning: Bad ASCII art for the 8-bit case
follows).

x = abcdefgh[2]
/ \
/ \
a b c d e f g h a b c d e f g h
& 1 0 1 0 1 0 1 0 & 0 1 0 1 0 1 0 1
= a 0 c 0 e 0 g 0 = 0 b 0 d 0 f 0 h
>>1 = 0 a 0 c 0 e 0 g : : : :
\ : : : :
- + 0 a 0 c 0 e 0 g
= ? ? ? ? ? ? ? ? = y

This is the first step. Can you explain the rightmost
two bits of the final sum in terms of the number of 1's
in the rightmost two bits of the original x? How about
the other three pairs? With that explanation in mind,
can you diagram what happens to y in the next step, and
the significance of its two quartets of bits?

--
Eric Sosman
es*****@ieee-dot-org.invalid
Aug 30 '07 #4
ravi wrote:
ravi wrote:
Hello,
the code below calculate the number of bits set in an unsigned
integer.
Can you explain me the logic behind the code?

unsigned int x = Some number;

x=(0xaaaaaaaa&x )>>1+(0x5555555 5&x);
x=(0xcccccccc&x )>>2+(0x3333333 3&x);
x=(0xf0f0f0f0&x )>>4+(0x0f0f0f0 f&x);
x=(0xff00ff00&x )>>8+(0x00ff00f f&x);
x=x>>16+(0x0000 ffff&x));
You need to add parentheses around the shift expression for the
calculation to work correctly.

--
Thad
Aug 30 '07 #5

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

Similar topics

60
7248
by: Fotios | last post by:
Hi guys, I have put together a flexible client-side user agent detector (written in js). I thought that some of you may find it useful. Code is here: http://fotios.cc/software/ua_detect.htm The detector requires javascript 1.0 to work. This translates to netscape 2.0 and IE 3.0 (although maybe IE 2.0 also works with it)
2
1533
by: Sam | last post by:
I'm working on a small application and I am stuck on the logic behind one of the queries I want to write. I've always considered myself to be a good problem solver and it depresses me that I can't figure this out. I don't really need any SQL syntax or anything, just help with ANDs, ORs, NOTs, etc... I have a table that has a column for a specific action. Each row in the table represents when an action is taken on a particular item. The...
7
2167
by: Stephen | last post by:
I have some code which I call from a custom validator however I seem to have got the logic wrong and im having trouble figuring out how to write my code to get things to work the way I require. Below is the script I currently use and what it does along with what I would like it to do. Can someone please help me work how I can fix this. <script> function ValidateDropDownOrCheckBox(sender, args) { if ( document.forms.DropDownList1.value...
3
1519
by: mca | last post by:
Hi everyone, I'm new to asp.net and i have a question about separating the html code from the programming code. i have an unknown numbers of entries in my table. I want to make a hyperlink for every entry in my table. So i query the database and get for example 3 entries back. So in a while loop i can make 3 hyperlinks with response.write(.......) etc.
5
6863
by: Steven Smith | last post by:
I was flicking through the windows accesories programs for some inspiration for todays vb challenge when I came accross the calculator program & thought that looks easy I could do that. However it hasn't turned out to be as easy as I first anticipated due to a calculators strange logic I done a bit of research on the web to see what I could come up with and I found this following page which outlines the ideas behind a calculator...
0
1587
by: fiona | last post by:
FOR IMMEDIATE RELEASE Catalyst release low cost logic processing tool 87% of defects in software are errors in logic Yucca Valley, CA, September 2006 - Catalyst Development Corporation, publisher of SocketWrench and SocketTools, today announced the release of its first application software, a logic processing software tool. LogicGem is designed to provide a familiar, easy-to-use way to create,
14
3561
by: rabbitrun | last post by:
Hi Everyone, I work for a financial company. I am planning to give a presentation to rest of the development team (15 people) here on moving server side logic to client-side javascript for an internal intranet application rewrite. This approach will definitely stir up hot debate from hardcore server-side Java folks who wants to do UI stuff even on the server!. Since I am pretty much known as the JS or UI Guy of the group, my Boss...
2
1715
by: Matthew Woodcraft | last post by:
John Salerno <johnjsal@gmailNOSPAM.comwrote: You probably could, but it's best not to unless you're somehow forced to. In practice, the interface that you want your 'logic' layer to provide to the GUI is likely to depend on some of the details of how the GUI works. If you did the lower levels first without having any idea at all of
1
2544
by: nicom53 | last post by:
i am writing a pacman game for a school project and i am having some problems with getting the logic so that pacman will not walk through the inner walls. I am also having a problem when the ghosts pass over a dot and not being able to leave one behind. My teacher gets us to use "Ready To Program Java"... i will send my current project to whoever can help
0
8428
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
8851
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
8528
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
8627
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
7356
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...
0
5649
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
4175
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...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1976
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.