I want to get the values of INT_MIN
and INT_MAX
. I've tried ~0
and ~0 >> 1
since the leftmost bit is a sign bit but I got -1
for both of them.
It's so confused that why ~0
doesn't turn out to be 0xffffffff
and ~0 >> 1
to be 0x7fffffff
?
Best Answer
Use:
Suffix 'U' for unsigned shift behavior.
See, what is
0
say in four bytes representation:Now
~
is bitwise not operator then flips all bits in0
as:Because of MSB =
1
this representation is treated as negative number and its magnitude is find using 2'complement math that is-1
.How?
What is
1
? it is:1's complement of
1
2'complement? Add
1
in one's complement, that is:this same as when you gets
~0
? that is why you are getting-1
output.Now >> shift operator?
In most implementation of C >> operator is defined as an arithmetic right shift, which preserves the sign bit MSB. So
~0 >> 1
is noting but-1
remains same.You requirement is what is called unsigned right shift
>>
and the behavior you needed can be find using unsigned number that is why I suffixedU
as0U
.How to print INT_MIN and INT_MAX?
Because printing INT_MIN and INT_MAX is bit tricky(because of undefined and implementation behavior of setting MSB and bit-overflow) in C so I have written a code as follows:
See it executing @codepad, it output is:
How does this code work?
Note for 32-bit number range is
[-2147483648, 2147483647]
that is equals to[-231, 231 -1 ]
.INT_MIN: -231 == -2147483648 is:
In expression
1U << ((sizeof(int) * CHAR_BIT) - 1)
, I shifts first bit the LSB(that is 1) to left most side at MSB, And because in C, setting signed bit is undefined behavior when operand is singed type so I used unsigned one 1U.Another point to note is I used CHAR_BIT a standard macro defined in limits.h that tells number of bits in one char in a C implementation (remember: A char is always one byte size but number of bits in one bytes can be different on different system not always guaranteed to be 8).
INT_MAX: 231 -1 == 2147483647