1

The https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html says

— Built-in Function: int __builtin_popcount (unsigned int x) Returns the number of 1-bits in x.

So todo the same, I tried the following code in c#

        long l8 = 9;
        int iCont = Convert.ToString(l8, 2).Split('0').ToList().FindAll(x=>x=="1").Count;

I wanted to double check with this question in stack overflow that, if this is wrong what I did or is there any built in functions do the same.

Naresh
  • 658
  • 1
  • 7
  • 22

1 Answers1

3

No, it is not. It will fail on any number with adjacent 1s in its binary representation, because they will be together in one string after Split('0') and so not match (x => x == "1"). Try 3, for instance.

Because string implements IEnumerable<char>, you can use an idea similar to yours while looking at the characters directly:

Convert.ToString(l8, 2).Count(c => c == '1')

There are other cleverer solutions, of course.

Community
  • 1
  • 1
user12864
  • 581
  • 4
  • 7
  • Thank you, I made this from that clever solutions. Completely test it though – Naresh Nov 19 '14 at 06:19
  • static int __builtin_popcount(long i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (int)(((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; } – Naresh Nov 19 '14 at 06:19