C code to count the number of '1' bits in an unsigned char

前端 未结 8 1763
孤街浪徒
孤街浪徒 2020-12-19 04:24

I need C code to return the number of 1\'s in an unsigned char in C. I need an explanation as to why it works if it\'s not obvious. I\'ve found a lot of code for a 32-bit nu

8条回答
  •  情深已故
    2020-12-19 04:58

    an unsigned char is a "number" in just the same way that a 32-bit float or integer is a "number", what the compiler deems them to represent is what changes.

    if you picture a char as its bits:

    01010011 (8 bits);

    you can count the set bits by doing the following:

    take the value, lets say x, and take x % 2, the remainder will be either 1 or 0. that is, depending on the endianness of the char, the left or right most bit. accumulate the remainder in a separate variable (this will be the resulting number of set bits).

    then >> (right shift) 1 bit.

    repeat until 8 bits have been shifted.

    the c code should be pretty simple to implement from my pseudocode, but basically

    public static int CountSetBits(char c)
    {
        int x = 0;
        int setBits = 0;
        while (x < 7)
        {
           setBits = setBits + c % 2;
           c = c >> 1;
           x = x + 1;
        }
    }
    

提交回复
热议问题