不使用宏定义计算 char 的限制

标签 c casting bitwise-operators

我试图使用以下表达式计算 char 类型的限制。

(char)(~(unsigned char)0 >> 1)

我预计它等于 127,但答案是 -1。
然后我替换了这个表达式。

~(unsigned char)0 

(unsigned char)~0

这个给出了正确答案 那么这两个有什么不同

最佳答案

(char)((unsigned char)~0 >> 1) 是 127 的原因很明显 - 你有 0xFFFFFFFF,将它转换为 unsigned char,你得到 0xFF,移位 1 然后你有 0x7F 或 127。

奇怪的是第一个错误的原因:您将零转换为 unsigned char。然后你补充那个。但是运算符 ~ 实际上提升了它的操作数:

The integer promotions are performed on the operand, and the result has the promoted type.

(n1570 第 6.5.3.3 节)

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions

(n1570 第 6.3.1.1 节)

因为 int 可以存储 unsigned char 的所有值,所以结果是一个 int。你将它移动一个,然后转换,结果是 -1

关于不使用宏定义计算 char 的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604571/

相关文章:

C 在 for 循环上的基本交互

mysql - 在 mysql MEMORY/HEAP 表中允许 TEXT 列的变通方法

php - 将索引数组转换为对象

c - 在 C 中屏蔽和提取位

c++ - 这里到底发生了什么?

c - 我没有得到输出。当我输入书籍数量时,它崩溃了..我不知道为什么!!!我是新C

c - 从文件中读取名称和字符

c - C中的宏....请给出解决方案

java - 在哪种情况下应该使用 toArray() 和 toArray(T[] a) 的重载版本?

c++ - -Wconversion warning while using operator <<= on unsigned char