比较有符号和无符号字符 [英] Comparison signed and unsigned char

查看:305
本文介绍了比较有符号和无符号字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很奇怪.我发现误会了.我使用带有字符的gcc作为签名字符.我一直认为,在比较表达式(和其他表达式)中,如有必要,带符号的值会转换为无符号的值.

It seems so strange. I found misunderstanding. I use gcc with char as signed char. I always thought that in comparison expressions(and other expressions) signed value converts to unsigned if necessary.

int a = -4;
unsigned int b = a;
std::cout << (b == a) << std::endl; // writes 1, Ok

但是问题在于

char a = -4;
unsigned char b = a;
std::cout << (b == a) << std::endl; // writes 0

如果不只是按位操作,比较运算符的魔力是什么?

what is the magic in comparison operator if it's not just bitwise?

推荐答案

根据C ++标准

6如果两个操作数均为算术或枚举类型,则通常 对两个操作数执行算术转换;每个 如果指定的关系为真,则运算符应为true,并且 如果为假,则为false.

6 If both operands are of arithmetic or enumeration type, the usual arithmetic conversions are performed on both operands; each of the operators shall yield true if the specified relationship is true and false if it is false.

所以在这个表达式中

b == a

示例

char a = -4;
unsigned char b = -a;
std::cout << (b == a) << std::endl; // writes 0

两个操作数都转换为类型int.结果,带符号的char扩展了其带符号的位,并且两个值不相等.

the both operands are converted to type int. As the result signed char propagets its signed bit and two values become unequal.

为演示效果,请尝试运行此简单示例

To demonstrate the effect try to run this simple example

{
    char a = -4;
    unsigned char b = -a;

    std::cout << std::hex << "a = " << ( int )a << "'\tb = " << ( int )b << std::endl;

    if ( b > a ) std::cout << "b is greater than a, that is b is positive and a is negative\n";
}

输出为

a = fffffffc'   'b = 4
b is greater than a, that is b is positive and a is negative

直到现在我才看到变量的定义必须看起来像

Only now I have seen that definitions of the variables have to look as

    char a = -4;
    unsigned char b = a;

那是b定义的负号.

这篇关于比较有符号和无符号字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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