Bleamer
Bleamer

Reputation: 647

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;

Upvotes: 8

Views: 7645

Answers (3)

ouah
ouah

Reputation: 145919

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.

Upvotes: 1

Stephen Canon
Stephen Canon

Reputation: 106317

Val & 0x0000FFFF is exactly the same as Val & 0xFFFF; both expressions have type int, and the result lies strictly in the range [0,65535]. (Assuming a 32-bit int type as stated by the questioner).

When you assign this result to a short, the value is unaltered if it is less than SHRT_MAX. If it is greater than SHRT_MAX (which is probably 32767 on your platform), the behavior is implementation-defined[1].

If you assign the result instead to an unsigned short, which is required to be able to represent all possible values that can result from your expression, then the result will be fully specified by the standard.


  1. In practice, on nearly all modern systems the result will be simply what you get from interpreting those 16 bits as a short, which is probably what you expect.

Upvotes: 0

struct
struct

Reputation: 604

The C99 language specification says that "usual arithmetic conversions apply" when doing a bitwise AND, val is already an integer and the hex constant should be an integer too (see page 56) because it's the first type which can represent it. Both casting and assigning should truncate the int into a short, but you shouldn't lose any data in this case.

Upvotes: 0

Related Questions