c++ - 将 long 转换为 int 与使用按位 AND 以获得 4 个最低有效字节之间有什么区别?

标签 c++ casting bit-manipulation bitwise-and

我知道为了获得 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/

相关文章:

c# - 可以在 C# 中向下转换为没有数据成员的派生类吗?

java - 如何在 OpenCL 中将 int 转换为 float?

bit-manipulation - 位操作代码的重要性?

c++ - Windows 上 C++ 中的位图操作

c++ - 计算给定单词在大于 10 亿个单词的文本语料库中出现的次数

c++ - 在我的 linux 中调用了哪个版本的 close(),来自 posix lib 还是内核?

java - 测试方法的返回类型是否为数字?

c++ - 如何编写返回仅存在于类中的类型的成员函数?

python - 仅使用按位运算符的两个数字的总和?

c++ - 位运算会导致程序运行变慢吗?