c++ - 将大数字类型转换为较小类型

标签 c++ types

我环顾四周,找不到类似的问题,如果以前有人问过,请道歉。

我只是在玩类型和数字,我想知道是否可以保证以下行为。 如果我将 2 个变量声明为

unsigned char BIT_8 = 0;
unsigned short int BIT_16 = 0xFF01;

然后执行以下操作(暂时忽略 C 样式转换,除非这会影响它?)

cout << "BIT_16: " << BIT_16 << "\n";
cout << "BIT_8: " << (int)BIT_8 << "\n";
BIT_8 = BIT_16;
cout << "BIT_8 after: " << (int)BIT_8 << "\n";
BIT_8 = BIT_16 >> 8;
cout << "BIT_8 after shift: " << (int)BIT_8 << "\n";

我得到了输出

BIT_16: 65281
BIT_8: 0
BIT_8 after: 1
BIT_8 after shift: 255

如果我将 16 位类型转换为 8 位类型,是否保证会丢失前导字节?还是未定义,上面的结果是运气?

最佳答案

Is it guaranteed that if I cast a 16 bit type to an 8 bit type that the leading byte will be lost?

取决于您使用的是有符号类型还是无符号类型(请参阅第 4.7 节第 2 节和第 3 节):

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n 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).]

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++ - 将大数字类型转换为较小类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6752567/

相关文章:

c++ - 使用 std::stream 接口(interface)创建一个日志记录对象

c++ - 在 C++ 中使用特征

c++ - 使用抽象基类型在 C++ 中进行类型推断

java - java 是否包含名为 "Item"的数据类型?

java - 为什么这会返回 Infinity? ( java )

c++ - 继承的成员函数似乎未声明,这是怎么回事?

C++ get 方法 - 按值或按引用返回

c++ - Visual Studio 2013 C++类属性初始化问题

c - 当我们声明双指针(**q)时int/char到底是什么

XSLT 从 DTD 获取属性类型