Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 32-bit integer value to unsigned 16-bit integer

What does the C standard say about:

uint32_t a = 0x11223344;
uint16_t b = a;

When printed, I am getting 0x3344, which makes sense; so this must be legal and correct behaviour?

like image 379
Mark Avatar asked Mar 04 '23 19:03

Mark


1 Answers

What the C standard says boils down to the fact that 0x11223344 is converted to uint16_t by calculating the value modulo 216, which is 0x3344.

However, the process by which it gets there has several steps:

uint16_t b = a; is a declaration with an initialization, which is discussed in C 2018 6.7.9 11:

The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

So the rules for simple assignment apply. These are discussed in 6.5.16.1 2:

In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

The “type of the assignment expression” is the type of the left operand, per 6.5.16 3:

The type of an assignment expression is the type the left operand would have after lvalue conversion.

(In this case, there is nothing remarkable about lvalue conversion; the object uint16_t b would simply become a uint16_t value, so the type is uint16_t.)

The type of uint16_t is, of course, an unsigned 16-bit integer, per 7.20.1.1 1:

The typedef name uintN_t designates an unsigned integer type with width N and no padding bits.

Note that, as an unsigned 16-bit integer, its maximum value is 65535, and one more than that is 65536 (216). This is relevant for the final step, the conversion from the right operand to uint16_t, which is discussed in 6.3.1.3 1 and 2:

When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.

When we subtract 65536 (0x10000) from 0x11223344 0x1122 times, the result is 0x3344, which can be represented by a uint16_t, so that is the result of the conversion.

like image 163
Eric Postpischil Avatar answered Apr 06 '23 03:04

Eric Postpischil