tom502
tom502

Reputation: 701

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

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?

Upvotes: 26

Views: 21790

Answers (1)

fredoverflow
fredoverflow

Reputation: 263138

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.

Upvotes: 32

Related Questions