Yi's Blog

思绪来得快,去得也快

Reverse a char

I met this problem in one interview: How to reverse a char? It took me a long time to figure out which I thought was very easy.

#include <iostream>
using namespace std;

unsigned char reverse_char(unsigned char in) {
    unsigned char high = 0x80;
    unsigned char res = 0x0, tmp = 0x0;
    for (int i=7; i>=0; i--) {
        tmp = (in&0x1)<<i;
        in = in>>1;
        res = (res&~high)|tmp;
        high = high>>1;
    }
    return res;
}

int main(int argc, char *argv[]) {    
    printf("%x\n", reverse_char(0xc4));
}

You have to pay attention to the difference of char and unsigned char.

More info about signed char: What does it mean for a char to be signed? - Stack Overflow

- EOF -