unsigned char型C = 255" 11111111"或不? [英] Unsigned char c = 255 is "11111111" or not?

查看:326
本文介绍了unsigned char型C = 255" 11111111"或不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的问题code:

Here is my problem code:

#include "stdio.h"

int main()
{
        char a = -1;
        unsigned char b = 255;
        unsigned char c = 0;
        if((~a) ==  c)
                printf("OK 1");
        else
                printf("bad 1");
        printf("\n");
        if((~b) ==  c)
                printf("OK 2");
        else
                printf("bad 2");
        printf("\n");
}

我预计打印:

OK 1

OK 2

不过,我得到OK 1和2不好!

But, I get OK 1 and bad 2!

如果 unsigned char型b 为255(11111111),那么〜乙方应00000000。为什么它不等于C吗?

If unsigned char b is 255 (11111111), then ~b should be 00000000. Why does it not equal c?

我在SUSE Linux的工作,用gcc。

I work on Linux SUSE, using gcc.

推荐答案

你要通过整数促销咬伤。当你这样做:

You're getting bitten by integer promotions. When you do:

~b == c

B C 都得到提升到 INT 。这意味着你真的这样做的:

b and c both get promoted to int. That means you're really doing:

~0x000000ff == 0

这结束了​​比较:

0xffffff00 == 0

不匹配。它可以在你的第一个情况,因为你的字符类型签名,并得到在促进符号扩展:

Which don't match. It works in your first case because your char type is signed, and gets sign extended in the promotion:

~a == c
~(-1) == 0
~0xffffffff == 0
0 == 0

这篇关于unsigned char型C = 255" 11111111"或不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆