Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c++ - 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.

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;

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 << "
";

I get the output

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Depends on whether you are working with signed or unsigned types (see section 4.7 §2 and §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.

Since you are working with unsigned types, the behavior is well-specified.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...