c - 整数转换排名和提升

标签 c integer type-conversion

阅读有关整数提升和整数转换排名的信息,我发现了这个 link

  • 1.If both operands have the same type, then no further conversion is needed.

  • 2.Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

  • 3.Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

  • 4.Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

  • 5.Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

第 1 2 3 点完全清楚,但我仍然没有针对案例 4 和 5 提出示例。有人可以提供有关任何实现的示例吗?

据我所知,整数转换等级是:

_Bool < char < short < int < long < long long int

无论与类型相关的字节大小都等于或大于。对吧?

关于从一种类型到另一种类型的提升或转换。添加到最低类型的位是零或 1 还是最左边的位对此有影响?

我想知道位 View 中的过程,尤其是转换过程。

对于整数提升,它始终可以毫无疑问地保持值和符号。

最佳答案

如果你有一个无符号类型,它的等级比它正在运行的有符号类型小,并且它们有不同的大小,那么情况 4 适用。情况 5 那么如果两者是相同的尺寸

例如,在我的系统上,int 是 32 位的,long 是 64 位的,long long 是 64 位的。如果您有以下情况:

unsigned int a;      // range: 0 to 4294967295
long b;              // range: -9223372036854775808 to 9223372036854775807

unsigned long c;     // range: 0 to 18446744073709551615
long long d;         // range: -9223372036854775808 to 9223372036854775807

对于涉及 ab 的表达式,它们是 unsigned intlong,任何有效的 unsigned int 可以放入一个long。所以 a 在这种情况下被转换为 long

反之,对于包含 cd 的表达式,它们是 unsigned longlong long,a long long 不能保存 unsigned long 的所有值。所以两个操作数都转换为 unsigned long long

关于位级别的提升/转换过程中发生的情况,我们首先假设较低级别的类型小于较高级别的类型,并且有符号类型使用 2 的补码表示。

对于从 32 位 int 到 64 位 long 的转换,如果值为正数,则在左侧添加包含所有 0 位的 4 个字节。如果该值为负数,则在左侧添加包含所有 1 位的 4 个字节。例如,值 5 的表示从 0x00000005 更改为 0x0000000000000005。对于值 -5,表示从 0xfffffffb 更改为 0xfffffffffffffffb

关于c - 整数转换排名和提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38854596/

相关文章:

java - "If the number is contained in the text and is repeated, return the sum of the number for each time it is repeated. Otherwise return 0."

algorithm - 钳位到系列中的下一个最低值

generics - 使用泛型进行对象转换

javascript - 为什么 C# 和 ECMAScript ISO 标准可以免费获得,而 C/C++ 却不能?

C:如何用指针数组生成固定数量的对象

c - 在 list_for_each_entry 中使用 break 是否安全?

c - 如何在GDB中调试fork-exec进程的入口点?

java - 类型不匹配 : cannot convert from Integer to int

python - 使用字典将 python 数据类型转换为其他语言的数据类型

c++ - 将浮点 vector 重新解释为无符号字符数组并返回