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 newreg=0x0;
    uint32_t bit=0x0;
    for (int i=0;i<=31;i=i+2){
        bit=(reg&(1<<i))?1:0;
        //printf("%d\n",bit);
        bit=bit<<(i/2);
        //printf("%d\n",bit);
        newreg|=bit;

    }
    return newreg;
}

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

Solving Approach

Iterate through the given number even (i=i+2) then check what are the bits are set or clear and accordingly assign 1 or 0, then left shift the bit to i/2 every loop instance and then add it to the main variable.

 

 

Upvote
Downvote
Loading...

Input

85

Expected Output

15