count the bits ON
any idea how to design a function which returns the number of ON bits of an integer. ex, pass a number 1234 [Binary: 10011010010] returns 5, thanks
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
AlanPosted Jul 6, 2007, 4:11 AM
Jan MontanoPosted Jul 5, 2007, 10:04 PM
SamPosted Jul 5, 2007, 3:44 PM
AlanPosted Jul 5, 2007, 2:27 PM
SamPosted Jul 5, 2007, 12:34 PM
Since is uses maths instead of a convertion to string
it should be quicker (not 100% certain)
public static int ONBits(int x)
{
int count = 0;
while(x > 0)
{
if ((x % 2) == 1)
{
count++;
}
x >>= 1;
}
return count;
}
Jan MontanoPosted Jul 4, 2007, 10:23 PM
href=http://en.wikipedia.org/wiki/Binary_numeral_system#Decimal
I don't know if .Net has a buit-in function for converting decimal to binary values. listed below is one way of converting it.
static string ConvertToBinary(int decimalValue)
{
}
AlanPosted Jul 4, 2007, 6:53 PM
Try this:
using System;
class Program
{
static void Main()
{
int num = 1234;
int count = GetBitsOnCount(num);
Console.WriteLine("Number of bits on in {0} is {1}", num, count);
Console.ReadLine();
}
public static int GetBitsOnCount(int num)
{
string bits = Convert.ToString(num, 2);
int count = 0;
for(int i = 0; i < bits.Length; i++)
{
if (bits[i] == '1') count++;
}
return count;
}
}