Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a large number type to a smaller type

Tags:

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?

like image 672
tom502 Avatar asked Jul 19 '11 18:07

tom502


People also ask

What is implicit casting?

An implicit cast is a cast that the database server can invoke automatically when it encounters data types that cannot be compared with built-in casts. This type of cast enables the database server to automatically handle conversions between other data types.

What is integer casting?

Converting one datatype into another is known as type casting or, type-conversion. For example, if you want to store a 'long' value into a simple integer then you can type cast 'long' to 'int'. You can convert the values from one type to another explicitly using the cast operator as follows − (type_name) expression.

What does it mean to cast a data type?

Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.


1 Answers

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.

like image 191
fredoverflow Avatar answered Oct 18 '22 03:10

fredoverflow