Jeswang's Blog

盲目跟随还是独立去做,To be or not to be?

Reverse a Char

| Comments

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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 -

Comments