22. Extract Even Bits Only from 32-bit Register

Back To All Submissions
Previous Submission
Next Submission
#include <stdio.h>
#include <stdint.h>

uint32_t extract_even_bits(uint32_t reg) {
    // Your code here
    uint32_t mask = 0x55555555;
    // keep all even bits only
    reg &= mask;
    // use brian keringhan's algortihm to keep count and return all set bits right-compressed
    uint8_t count = 0;
    while (reg != 0) {
        reg &= (reg - 1);
        count++;
    };
    return (1 << count) - 1;
}

int main() {
    uint32_t reg;
    scanf("%u", &reg);
    printf("%u", extract_even_bits(reg));
    return 0;
}

Solving Approach

First we keep all even bits only, then we return the "right-compressed" extracted bits by using the count on the set bits. 

 

 

Was this helpful?
Upvote
Downvote