将大量类型转换为较小类型

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.

这篇关于将大量类型转换为较小类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将大量类型转换为较小类型

基础教程推荐