Count Set Bits in an 8-bit Register

Code

#include <stdio.h>
#include <stdint.h>

uint8_t count_set_bits(uint8_t reg) {
    //Bitshift to right (for size of reg)
    //Check with mask of 0x01 to check first bit
    //If 1, add to counter
    int counter=0;
    while (reg){
        if(reg & 0x01){
            counter++;
        }
        reg = reg >> 1;
    }
    return counter;
}

int main() {
    uint8_t reg;
    scanf("%hhu", &reg);
    printf("%u", count_set_bits(reg));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Expected Output

0