Bit Reversal in an 8-bit Value

Code

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

uint8_t reverse_bits(uint8_t val) {
    // Your logic here
    uint8_t pre = val;
    uint8_t nghich =0;
    for(int i = 0;i<=7;i++){
        val = (val >> i) & 0x01; 
        if(val == 1){
            nghich |= 1 << (7-i); //note 7 - i if 1>>i => 0001 => 0000. not 010000 
        }
        val = pre;
    }
    return nghich;
}

int main() {
    uint8_t val;
    scanf("%hhu", &val);

    uint8_t result = reverse_bits(val);
    printf("%u", result);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

26

Expected Output

88