Extract Even Bits Only from 32-bit Register

Code

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

uint32_t extract_even_bits(uint32_t reg) {
    uint32_t even_reg = 0;
    int dest_bit = 0; // This tracks where to put the bit in the result

    // Loop through even positions: 0, 2, 4, ..., 30
    for(int i = 0; i < 32; i += 2) {
        // 1. Isolate the bit at position 'i'
        // (reg >> i) & 1  gives us just the bit at that position
        uint32_t bit = (reg >> i) & 1;

        // 2. Place that bit into the 'dest_bit' position in our result
        even_reg |= (bit << dest_bit);

        // 3. Move the destination pointer for the next even bit
        dest_bit++;
    }
    return even_reg;
}

int main() {
    uint32_t reg;
    if (scanf("%u", &reg) == 1) {
        printf("%u\n", extract_even_bits(reg));
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

85

Expected Output

15