90. Bit Reversal in an 8-bit Value

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

// Reverse bits in an 8-bit value
uint8_t reverse_bits(uint8_t val) {
    uint8_t result = 0;

    for (int i = 0; i < 8; i++) {
        // Shift result left to make room for next bit
        result <<= 1;

        // Take LSB from input and add to result
        result |= (val & 1);

        // Shift input right to process next bit
        val >>= 1;
    }

    return result;
}

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

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

Why Bit Reversal?

Used in:

  • CRC and parity computation
  • Bitstream processing
  • SPI/UART LSB-first data handling
     

Logic Summary

  • Initialize result = 0
  • Loop 8 times:
    • Shift result left by 1
    • Copy the last bit of val to result
    • Shift val right
  • End result is val reversed bit by bit
     
Loading...

Input

26

Expected Output

88