Bitwise operation return type in C

I have an int (32) Val value packaged into a form

 ---------------------------------------- | 32-XXXXXXXXX-16 | 15-short-int-val-0 | ---------------------------------------- 

When extracting a short integer value from this Val , if I perform an operation

 short temp = Val & 0x0000FFFF; 

What will be the return type of the Val & 0x0000FFFF ? Do I need to enter a value for (short)(Val & 0x0000FFFFF) in order to have the correct data stored in temp ?

Doubt arises because I assume that hexadecimal numbers are essentially treated as unsigned integers.

How is this operation different from performing

 short temp = Val & 0xFFFF; 
+7
c type-conversion
source share
3 answers

Suppose 32-bit int , 16-bit short and 8-bit char .

 short temp = Val & 0x0000FFFF; 

Val is of type int . 0x0000FFFF , which is the same as 0xFFFF , is of type int .

Then the expression Val & 0x0000FFFF also of type int and is implicitly converted to short when the temp object is initialized.

So:

What will be the return type of the Val operation and 0x0000FFFF?

See above, int .

Do I need to enter a value for input (short) (Val and 0x0000FFFFF) in order to have the correct data stored in temp?

See above, no, because the expression is implicitly converted to short when the temp object is initialized.

Confidence arises because I assume that hexadecimal numbers are essentially treated as unsigned integers.

This is a false match, since here 0x0000FFFF has a signed int type.

0
source share

The C99 language specification says that when performing bitwise AND, "normal arithmetic conversions" are applied, val already an integer, and the hexadecimal constant must also be an integer (see page 56), because this is the first type that can represent. Both casting and assignment should truncate int to short , but you should not lose any data in this case.

0
source share

Val & 0x0000FFFF exactly matches Val & 0xFFFF ; both expressions are of type int , and the result lies strictly in the range [0.65535]. (Assuming a 32-bit int type, as indicated by the interrogator).

Assigning this result to short does not change the value if it is less than SHRT_MAX . If it is larger than SHRT_MAX (which is probably 32767 on your platform), the behavior is determined by the implementation [1].

If you assign a result instead of an unsigned short , which should be able to represent all possible values ​​that may arise from your expression, then the result will be fully defined by the standard.


  • In practice, in almost all modern systems, the result is simply what you get from interpreting these 16 bits as short , which is what you probably expect.
0
source share

All Articles