Extract Even Bits Only from 32-bit Register

Code

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

uint32_t extract_even_bits(uint32_t reg) {
    // Your code here
    uint32_t mask = (0x55555555 & reg);
    uint32_t result = 0;
    uint32_t out_pos = 0; //position of current output bit in the final result value
    uint32_t bit = 0;
    for(uint32_t i = 0; i < 32; i+=2){
        bit = ((reg >> i) & 1U); //shifting the latest even bit of the reg to the LSB
        result |= (bit << out_pos);
        out_pos++; //increase the output position by 1, i.e shifting 1 bit to the left
    }
    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