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 result = 0;
    uint8_t pos = 0;

    for(uint8_t i = 0; i < 32; i += 2){
        uint32_t bit = (reg >> i) & 1;
        result |= (bit << pos);
        pos++;
    }
    return result;
}

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

Solving Approach

  • Loop through even bit positions (0, 2, 4, …, 30).
  • Extract each bit → (reg >> i) & 1.
  • Pack them consecutively into result using shifting.
  • Return compressed value.

 

 

Upvote
Downvote
Loading...

Input

85

Expected Output

15