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:

  • 0xFFFFFFFF但这是Long而不是Int
  • 0xFFFFFFFF.toInt() which is -1
  • -0xFFFFFFFF.toInt()等于1
  • 0x7FFFFFFF是2147483647是Int.MAX_VALUE
  • -0x7FFFFFFF which is -2147483647 which is Int.MIN_VALUE+1
  • 0xFFFFFFF which is 268435455 in decimal
  • 0x0FFFFFFF which is also 268435455 in decimal

But I can't figure out what hexadecimal integer literal can be used to represent Int.MIN_VALUE.

我希望答案不会让我觉得自己很愚蠢...

推荐答案

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

可以看到,最左边的位是0,因此这是32位表示中的正积分.根据2's complement的定义和示例,最小32位负值最左边的位是1,后面是0:

1000 0000 0000 0000 0000 0000 0000 0000

___8 0 0 0 0 0 0 0

一共是0x80000000美元.

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)

这与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.

进一步阅读:

Kotlin相关问答推荐

Kotlin Coroutine()是如何工作的?S阻止了.

kotlin - 挂起简单方法调用链时可能存在冗余分支

合并状态流

如何使用 Kotlin Maven 更改 Minecraft 插件中的 Shulker GUI 标题

Kotlin 协程:flatMapLatest 什么都不发出

多个不同的指针输入

Kotlin 可打包类抛出 ClassNotFoundException

Kotlin RxJava 可空的错误

下拉通知面板时是否可以暂停Android中的任何视频(媒体播放器)应用程序?

如何在主线程上使用 Kotlin 协程 await()

如何从 Firestore 查询中排除元素?

如何在顶级函数中使用 koin 注入依赖项

launch 仅从 Kotlin 1.3 开始可用,不能在 Kotlin 1.2 中使用

Kotlin val difference getter override vs assignment

Android 与 Kotlin - 如何使用 HttpUrlConnection

用Gradle Kotlin DSL构建源jar?

Kotlin - computed var 属性的用处?

如何将 CameraView 与 Jetpack Compose 一起使用?

Kotlin var lazy init

你如何在 Kotlin 中注释 Pair 参数?