how does one write a hexadecimal integer literal that is equal to
Int.MIN_VALUE (which is
-2147483648 in decimal) in Kotlin?
AFAIK, an Int is 4 bytes...and sometimes it seems like 2's complement is used to represent integers...but I'm not sure. I've tried the following hex literals to help myself understand the system:
0xFFFFFFFFbut this is a
Long, not an
0xFFFFFFFF.toInt()which is -1
-0xFFFFFFFF.toInt()which is 1
0x7FFFFFFFwhich is 2147483647 which is
-0x7FFFFFFFwhich is -2147483647 which is
0xFFFFFFFwhich is 268435455 in decimal
0x0FFFFFFFwhich is also 268435455 in decimal
But I can't figure out what hexadecimal integer literal can be used to represent
I hope the answer doesn't make me feel stupid...
Int represents a 32-bit signed integer. 32 bits means 8 hex digits:
___7 F F F F F F F
0111 1111 1111 1111 1111 1111 1111 1111
As you can see the left-most bit is 0 thus this is a positive integral in a 32 bit representation. By 2's complement definition and example the minimal 32-bit negative value will have
1 at left-most bit followed by
1000 0000 0000 0000 0000 0000 0000 0000
___8 0 0 0 0 0 0 0
In Kotlin you need to prepend the
- sign to denote negative
Int which is not true in Java. Consider following example
println(0x7FFFFFFF) // -> prints 2147483647 (Integer.MAX_VALUE) println(-0x80000000) // -> prints -2147483648 (Integer.MIN_VALUE) println(0x80000000) // -> prints 2147483648 (does not fit into Int)
It's not the same as in Java:
System.out.println(0x7FFFFFFF); // -> prints 2147483647 (Integer.MAX_VALUE) System.out.println(-0x80000000); // -> prints -2147483648 (Integer.MIN_VALUE) System.out.println(0x80000000); // -> prints -2147483648 (Integer.MIN_VALUE)
This is in line with Kotlin spec although the overflow behavior of hexadecimal literals is yet to be defined.
If you just want INT_MIN value and you are talking about a 4 bytes integer, and since no one has mentioned it before, you can just write:
The neg operand
~ (.inv()) will automatically switch bits from 1 to 0 (which is what happens when you overflow).
User contributions licensed under CC BY-SA 3.0