开发者

What is wrong with my algorithm?

Alright, I've cooked up some code to reverse hex characters around as part of a fun exercise I made up.

Here is what I have at the moment:

#include <stdio.h>  
int main() {  
    char a,b,c;  
    while (1) {  
        c = getchar();  
        if (!feof(stdin)) {  
            a = c % 16;  
            b = (c - a) / 16;  
            c = (a*16) + b;  
            putchar(c);  
        }else{break;}  
    }  
return 0开发者_Go百科;  
}  

It works well for most values. For example, 0xA0 becomes 0x0A etc...

However, it's not playing well with values beginning with 'F'.

0xF1 becomes 0x10

0xFF becomes 0xF0

etc...

Can somebody point me into the right direction?


If char is signed on your system, then when the upper nibble of c is f, c is negative, and c%16 will give a negative result.


You're using a signed (on your machine) data type. Switch it to unsigned and it should works properly.


I dont know why someone is doing *, /, % operations while simple bitwise operations can do such things.

a = (c & 0x0F) << 4;
b = (c & 0xF0) >> 4;
c = a|b;


getchar and putchar return and take ints. Even better than this they use the value of the char cast to an unsigned char which means that for all valid characters putchar will return a positive value. This is needed for your algorithm as you use % and you would otherwise need to rely on implementation defined behaviour.

If you assign the value of getchar to an int then you can test whether the read failed for any reason (not just end-of-stream) by comparing against EOF. Using feof is then not necessary - it wasn't sufficient before.

E.g.

int main(void) {  
    int c;  
    while ((c = getchar()) != EOF) {  
        /* algorithm goes here */
        putchar(c);  
    }  
    return 0;  
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜