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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
AlanRank #669 · 3.6K reputationPosted Jul 4, 2007, 2:53 PM EDT
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;
}
}
Jan MontanoRank #1,295 · 1.3K reputationPosted Jul 4, 2007, 6:23 PM EDT
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)
{
}
Sam112 reputationPosted Jul 5, 2007, 8:34 AM EDT
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;
}
AlanRank #669 · 3.6K reputationPosted Jul 5, 2007, 10:27 AM EDT
Sam112 reputationPosted Jul 5, 2007, 11:44 AM EDT
Jan MontanoRank #1,295 · 1.3K reputationPosted Jul 5, 2007, 6:04 PM EDT
AlanRank #669 · 3.6K reputationPosted Jul 6, 2007, 12:11 AM EDT