我知道为了获得 long
类型的数字的 4 个最低有效字节,我可以将其转换为 int
/unsigned int
或使用按位与 (& 0xFFFFFFFF
)。
This代码产生以下输出:
#include <stdio.h>
int main()
{
long n = 0x8899AABBCCDDEEFF;
printf("0x%016lX\n", n);
printf("0x%016X\n", (int)n);
printf("0x%016X\n", (unsigned int)n);
printf("0x%016lX\n", n & 0xFFFFFFFF);
}
输出:
0x8899AABBCCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
0x00000000CCDDEEFF
这是否意味着所使用的两种方法是等效的?如果是这样,无论平台/编译器如何,它们总是产生相同的输出吗?
此外,为了这个问题的目的,在转换为 unsigned int
而不是 int
时是否有任何问题或陷阱?
最后,为什么是output如果将数字 n
更改为 unsigned long
是否相同?
最佳答案
方法肯定不一样
根据整数转换规则(参见,例如 this 在线 c++11 标准),从一种整数类型到另一种整数类型的转换(例如通过显式转换)取决于目标类型是有符号的还是无符号的.如果目标类型是无符号的,则可以依赖于“模 2n”截断,而对于有符号的目标类型,则可以利用实现定义的行为:
4.7 Integral conversions [conv.integral]
2 If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]
3 If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
关于c++ - 将 long 转换为 int 与使用按位 AND 以获得 4 个最低有效字节之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56332658/