search

Home  >  Q&A  >  body text

ios - 我都不好意思来提这个问题,但为了弄明白,还是请大家帮帮我吧

今天在看一本objective-c的教程,里面第6章讲到关于整数。
里面有一段话,摘抄如下:

通常会用第3章介绍过的带描述性的类型来声明整数。
char a;//8
short b;//通常是16位(视平台而定)
int c;//通常是32位(视平台而定)
long d;//32位或64位(视平台而定)
long long e;//64位

然后,我看到了后面的一段示例代码:

#include <stdio.h>
int main (int argc, const char * argv[])
{
    int x = 255;
    printf("x is %d.\n", x);
    return 0;
}

输出结果为:
x is 255.

但,我突发奇想,想试验一下其他的整数声明,我就把int x = 254改成了char x = 254
结果,输出结果为:
x is -2.

这个结果太出乎我意外了(新人,但皮厚,可随便取笑。),char不是8位么?应该可以保存
0-255之间的整数啊,为什么等于254,输出为-2(还蛮有规律的,如果是255,就是-1)了啊?
或者说,我的理解一直有误,虽然8位的无符号整数可保存0-255之间的整数,但这个保存0-255之间的整数,并不是我现在认为的可以char x = 254?

精壮的大神们,请帮帮我吧,虽然对你们来讲是常识问题,但我扒拉了好久google也没有弄明白啊,倒是越来越糊涂,我还找了本C的教程来看整数这一段,也是没明白。

精壮的大神们,来吧~

ringa_leeringa_lee2769 days ago272

reply all(1)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:02:27

    Although I don’t understand objC, and I don’t understand C at all, I’m not surprised at all when I see -2.

    8-bit unsigned range is 0~255
    8-bit signed range is -128~127

    So how to express negative numbers? We hope that unsigned can use the same rules as signed for addition and subtraction. Therefore, the expression of negative numbers satisfies the formula -x = ~x + 1 (~x represents the complement of x), that is, in the case of 8 bits, 0xFF represents -1, and 0xFE represents -2,254 is also 0xFE

    Think about it in 8-bit mode

    254 + 2 == 0; //溢出
    -2 + 2 == 0;
    

    The addition and subtraction implementations used for signed and unsigned are consistent

    After writing this, I remembered that C seems to be %d => signed %ud or something like => unsigned?

    reply
    0
  • Cancelreply