Extract Even Bits Only from 32-bit Register

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

uint32_t extract_even_bits(uint32_t reg) {
    // Your code here
    uint32_t mask = 0x555555555;
    uint32_t x =  reg & mask;

    x = (x | (x >> 1)) & 0x33333333; // Move bits to groups of 2: ..ab..cd
    x = (x | (x >> 2)) & 0x0F0F0F0F; // Move to groups of 4: ....abcd
    x = (x | (x >> 4)) & 0x00FF00FF; // Move to groups of 8
    x = (x | (x >> 8)) & 0x0000FFFF; // Final result in bottom 16 bits
    return x;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

85

Expected Output

15