Reputation: 6322
I'm seeing strange behavior when I try to apply a right bit-shift within a variable declaration/assignment:
unsigned int i = ~0 >> 1;
The result I'm getting is 0xffffffff
, as if the >> 1
simply wasn't there. It seems to be something about the ~0
, because if I instead do:
unsigned int i = 0xffffffff >> 1;
I get 0x7fffffff
as expected. I thought I might be tripping over an operator precedence issue, so tried:
unsigned int i = (~0) >> 1;
but it made no difference. I could just perform the shift in a separate statement, like
unsigned int i = ~0;
i >>= 1;
but I'd like to know what's going on.
update Thanks merlin2011 for pointing me towards an answer. Turns out it was performing an arithmetic shift because it was interpreting ~0
as a signed (negative) value. The simplest fix seems to be:
unsigned int i = ~0u >> 1;
Now I'm wondering why 0xffffffff
wasn't also interpreted as a signed value.
Upvotes: 2
Views: 81
Reputation: 30823
It is how c compiler works for signed value. The base literal for number in C is int
(in 32-bit machine, it is 32-bit signed int
)
You may want to change it to:
unsigned int i = ~(unsigned int)0 >> 1;
The reason is because for the signed value, the compiler would treat the operator >>
as an arithmetic shift (or signed shift).
Or, more shortly (pointed out by M.M),
unsigned int i = ~0u >> 1;
Test:
printf("%x", i);
Result:
Upvotes: 1
Reputation: 11406
In unsigned int i = ~0;
, ~0
is seen as a signed integer (the compiler should warn about that).
Try this instead:
unsigned int i = (unsigned int)~0 >> 1;
Upvotes: 0