将两个字符加到简短结果中会导致错误的答案

时间:2019-03-30 22:50:36

标签: c casting

我有一个函数,旨在将两个字符加在一起的值变成一个短字符。似乎价值被切断或破坏了。

这是我的代码:

char rotate(char a, char b){
    unsigned short x = a + b;
    printf("init:%hu %hu = %hu\n", (unsigned char)a, (unsigned char)b,  (unsigned short)x);
    if(x > 255){
       x -= 255;
    }
    return (char) x;
}

unsigned char x = rotate((unsigned char)230, (unsigned char)100);
unsigned char y = rotate((unsigned char )200, (unsigned char)200);
unsigned char z = rotate((unsigned char) 230, (unsigned char)120);

结果是

init:230 100 = 74
init:200 200 = 65424
init:230 120 = 94

1 个答案:

答案 0 :(得分:1)

加法是用原始值完成的,而且是正确的。

unsigned short x = a + b;

现在显示的是转换后的值。

printf("init:%hu %hu = %hu\n", (unsigned char)a, (unsigned char)b, ....

打印char原始值。

#if CHAR_MAX <= INT_MAX
  printf("a:%d b:%d\n", a, b);
#else
  // this is rare
  printf("a:%u b:%u\n", a, b);
#endif

OP将看到第一个加法为init:-26 100 = 74,总和为74。


对于init:200 200 = 65424,原始char值为-56。 -56 + -56是-112。将-112分配给16位unsigned short(0-65535),则添加65536,然后分配。 -112 + 65536-> 65424