聘我网

新概念招聘3.0

二进制转十六进制程序bug

vote up0vote downstar

写了个小程序实现8比特的2/16进制转化:

#include <stdio.h>
int main(int argc,char*argv[]) {
    char *bin="11010011";
    char *a = bin;
    char num = 0;
    do {
        int b = *a=='1'?1:0;
        num = (num<<1)|b;
        a++;
    } while (*a);
    printf("%02X\n", num);
    return 0;
}

但是输出确是:

FFFFFFD3

而不是D3,这是什么问题?

 

2 个答复

vote up0vote downcheck
-char num = 0;
+unsigned char num = 0;

或者

-char num = 0;
+unsigned char num = 0;

char,unsigned charsigned char是不同的。

char被译成unsigned还是signed,依赖于具体实现,c/c++本身并没有规定。

如果只关心文本形式而不关心数值,应该用char

但如果依赖于数值,应该根据需要使用unsigned charsigned char

而要能完整表示所有的8比特二进制,数值范围是0~255,只能用unsigned char,当然如果是int就更没问题了。

D32进制为11010011,如果是signed char,最高位表示符号,根据补码其值为-45,当promotesigned int时,按照Sign extension进行保号操作,便成了FFFFFFD3

Sign extension is the operation, in computer arithmetic, of increasing the number of bits of a binary number while preserving the number's sign (positive/negative) and value. This is done by appending digits to the most significant side of the number, following a procedure dependent on the particular signed number representation used.

链接
vote up0vote down

补充一点,当promote转换(一般发生在位少向位多转化时;反过来转换一般直接就截掉了)时,会保值,也就是说转换前后值不会变,但内存结构可能变化。

链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.