All submissions

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 reg, i, j;
    
    i= 0x80;
    j= 0x1;
    reg= 0xFF;

    while (i != 0) {
        if ((i & val) == 0) {
            reg = reg ^ j;
        }     
        else {
            reg = reg | j;
        }
        i = i >> 1;
        j = j << 1;
    }
    return reg;
}

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

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

Solving Approach

Start with 0xFF in result register

Use two sliding masks : i slides left to right and j slides right to left

detect bits of 'value' by bitwise AND with the sliding i : 

this lets j set the bit (or clear it ) in the result 'register'

 

 

Loading...

Input

26

Expected Output

88