Casting a large number type to a smaller type(将大量类型转换为较小类型)
问题描述
我已经仔细环顾四周,但找不到类似的问题,所以如果之前有人问过这个问题,我深表歉意.
I've had a good look around and can't find a similar question so apologies if it has been asked before.
我只是在玩弄类型和数字,我想知道是否可以保证以下行为.如果我将 2 个变量声明为
I'm just playing around with types and numbers and I am wondering if the following behaviour can be guaranteed. If I declare 2 variables as
unsigned char BIT_8 = 0;
unsigned short int BIT_16 = 0xFF01;
然后执行以下操作(暂时忽略 C 样式转换,除非这会影响它?)
and then do the following (ignoring C style cast for now, unless that can affect it?)
cout << "BIT_16: " << BIT_16 << "
";
cout << "BIT_8: " << (int)BIT_8 << "
";
BIT_8 = BIT_16;
cout << "BIT_8 after: " << (int)BIT_8 << "
";
BIT_8 = BIT_16 >> 8;
cout << "BIT_8 after shift: " << (int)BIT_8 << "
";
我得到输出
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? or is it undefined and the above results are luck?
推荐答案
是否保证将 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):
Depends on whether you are working with signed or unsigned types (see section 4.7 §2 and §3):
如果目标类型是无符号,则结果值是与源整数一致的最小无符号整数(模 2^n,其中 n 是用于表示无符号类型的位数).[注意:在二进制补码表示中,这种转换是概念性的,位模式没有变化(如果没有截断).]
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.
由于您使用的是无符号类型,因此行为是明确指定的.
Since you are working with unsigned types, the behavior is well-specified.
这篇关于将大量类型转换为较小类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将大量类型转换为较小类型
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01