Count Set Bits in an 8-bit Register

Code

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

uint8_t count_set_bits(uint8_t reg) {
    uint8_t count = 0;
    
    // We iterate 8 times because it's an 8-bit register
    for (int i = 0; i < 8; i++) {
        // Check if the last bit is 1
        if (reg & 1) {
            count++;
        }
        // Right shift the register by 1 to process the next bit
        reg >>= 1;
    }
    
    return count;
}

int main() {
    uint8_t reg;
    // Note: %hhu is the correct format specifier for uint8_t
    if (scanf("%hhu", &reg) == 1) {
        printf("%u\n", count_set_bits(reg));
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Expected Output

0