Bit Reversal in an 8-bit Value

Code

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

uint8_t reverse_bits(uint8_t val) {
    // Your logic here
    val = ((val & 0x55) << 1) | ((val & 0xAA) >> 1);
    val = ((val & 0x33) << 2) | ((val & 0xCC) >> 2);
    val = ((val & 0x0F) << 4) | ((val & 0xF0) >> 4);
    return val;
}

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

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

Solving Approach

 

Mask based bit reversal

first it swaps the adjacent bits then swaps the adjacent pair of bits and then swaps the nibbles

 

Upvote
Downvote
Loading...

Input

26

Expected Output

88