Extract Even Bits Only from 32-bit Register

Code

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

uint32_t extract_even_bits(uint32_t reg) {
    uint16_t result = 0;
    int target_pos = 0;

    // We loop 16 times because there are 16 even positions in a 32-bit number
    for (int i = 0; i < 32; i += 2) {
        // 1. Isolate the bit at the even position 'i'
        // (reg >> i) & 1 picks the bit at index 0, 2, 4...
        uint32_t bit = (reg >> i) & 1U;

        // 2. Place that bit into the 'target_pos' (0, 1, 2, 3...)
        result |= (uint16_t)(bit << target_pos);

        // 3. Increment the target position for the next found bit
        target_pos++;
    }

    return result;
}

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