Extract Even Bits Only from 32-bit Register

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

uint32_t extract_even_bits(uint32_t reg) {
    // Step 1: Mask the even bits (0, 2, 4, ..., 30)
    // 0x55555555 is 0101 0101 0101 0101 0101 0101 0101 0101 in binary
    uint32_t x = reg & 0x55555555;

    // Step 2: Compact the bits. 
    // We shift the higher bits to the right to fill the gaps left by odd bits.
    x = (x | (x >> 1)) & 0x33333333; // Group bits into pairs
    x = (x | (x >> 2)) & 0x0F0F0F0F; // Group into 4-bit nibbles
    x = (x | (x >> 4)) & 0x00FF00FF; // Group into 8-bit bytes
    x = (x | (x >> 8)) & 0x0000FFFF; // Group into 16-bit word

    return x;
}

int main() {
    uint32_t reg;
    // Note: Using %u for unsigned int, but for bit manipulation 
    // hex (0x...) or manual binary checks are usually easier to verify.
    if (scanf("%u", &reg) == 1) {
        printf("%u\n", extract_even_bits(reg));
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

85

Expected Output

15