将大数字类型转换为较小类型 [英] Casting a large number type to a smaller type

查看:182
本文介绍了将大数字类型转换为较小类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很好的环顾四周,找不到一个类似的问题,如果以前被问过,请不要抱歉。

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风格的转换,除非可以影响它) / p>

and then do the following (ignoring C style cast for now, unless that can affect it?)

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? 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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆