Although there are pedantic points which can be made about compiler behaviour, the simple answer is that a signed int
with the top bit set is a negative number.
So if you do something which sets the top bit of an int
(a signed int, not an unsigned one), then ask the tools/library to show you the value of that int
, you'll see a negative number.
This is not a universal truth, but it's a good approximation to it for most modern systems.
Note that it's printf
which is making the representation here - because %d
formats numbers as signed. %u
may give the result you're expecting. Just changing the types of the variables won't be enough, because printf
doesn't know anything about the types of its arguments.
I would say that as a general rule of thumb, if you're doing bit-twiddling, then use unsigned int
s and display them in hexadecimal. Life will be simpler that way, and it most generally fits with the intent. (Fancy accelerated maths tricks are an obvious exception)