Jump to content
  • Advertisement
Sign in to follow this  
TEUTON

counting no of set bits in number

This topic is 4604 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is the question Write a fast way to count the number of set bits in an unsigned int Here is my code-
#include <iostream>

int main()
{
	int count=0;
	unsigned int x=50;
	while(x>0)
		{
		if(x&1)
			{
			++count;
			}
		x>>=1;
		}
	std::cout<<count;
return 0;
}

Is it fast or is ther any other better way?

Share this post


Link to post
Share on other sites
Advertisement
How does the question define "fast"? As in productivity/maintainability, or as in bit twiddling?

#include <bitset>
#include <iostream>

int main()
{
std::bitset<32> foo;
foo.set(5);
foo.set(10);
std::cout << foo.count() << "\n";
}





Will output: 2

[Edited by - Will F on April 8, 2006 12:13:31 AM]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!