Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type of bitwise operation in C

I have an int (32) value Val packed in form

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

When extracting the short integer value from this Val if I do the operation

short temp = Val & 0x0000FFFF;

What is will be the return type of the operation Val & 0x0000FFFF ? Do I need to type cast the value to (short)(Val & 0x0000FFFFF) to have correct data stored in temp?

The doubt arises since I assume hex numbers are inherently treated as unsigned integers.

How is the above operation different from doing

short temp = Val & 0xFFFF;
like image 327
Bleamer Avatar asked Jul 23 '13 10:07

Bleamer


1 Answers

Let's assume 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 as well.

The expression Val & 0x0000FFFF is then also of type int and is implicitly converted to short at initialization of temp object.

So:

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

See above, int.

Do I need to type cast the value to (short)(Val & 0x0000FFFFF) to have correct data stored in temp?

See above, no as the expression is implicitly converted to short at initialization of temp object.

The doubt arises since I assume hex numbers are inherently treated as unsigned integers.

This is a wrong asssumption as here 0x0000FFFF is of signed type int.

like image 195
ouah Avatar answered Oct 21 '22 21:10

ouah