unsigned char a, b;
a = 0x0f;
b = (~a) >> 4;
printf("0x%x", b);
输出为0xff;
因为
(~a) 被提升为 int 型的取反运算。
对于 MinGW gcc,int 型是 32 位, 因此 (~a) = 0xff ff ff f0, 所以截取后 b = 0xff。
第二个例子:
#include <stdio.h>
int main(void)
{
unsigned char a = 0xff;
char b = 0xff;
int c = a==b; // true, or false?
printf("C: %d\n",c);
}
你可能认为输出是1.其实是0。噢!
因为a,b 提升为整形int 来比较,a为255,而b 为-1.
为什么b 是-1 呢?
在 /usr/include/limit.h 中有定义:
/* Minimum and maximum values a `char' can hold. */
# ifdef __CHAR_UNSIGNED__
# define CHAR_MIN 0
# define CHAR_MAX UCHAR_MAX
# else
# define CHAR_MIN SCHAR_MIN
# define CHAR_MAX SCHAR_MAX
# endif
所以 char b 的范围是 -128 到 127 ,如果是超出了这个范围就会自动求补。如 char i =255; 运算时i 是-1. 如果char i=256; 编译器提示溢出。
604

被折叠的 条评论
为什么被折叠?



