我正在寻找一个类似于Kotlin中的JavaInteger.toHexString()的函数.有没有内置的东西,或者我们必须手动编写一个函数来将Int转换为String

推荐答案

您仍然可以通过调用java.lang.Integer上的静态函数来使用Java转换:

val hexString = java.lang.Integer.toHexString(i)

And, starting with Kotlin 1.1, there is a function in the Kotlin standard library that does the conversion, too:

fun Int.toString(radix: Int): String

返回指定radix中此Int值的字符串表示形式.

但是,请注意,Integer.toHexString()中的this will still be different,因为后者执行无符号转换:

println((-50).toString(16)) // -32
println(Integer.toHexString(-50)) // ffffffce

But with experimental Kotlin unsigned types, it is now possible to get the same result from negative number unsigned conversion as with Integer.toHexString(-50):

println((-50).toUInt().toString(16)) // ffffffce

Kotlin相关问答推荐

Kotlin -通过反射获得KProperty 1和CallableReference的实例

用浮点数或十进制数给出错误答案的阶乘计算

两个LocalDateTime之间的Kotlin差异

在 Kotlin 中,如何绑定扩展方法以在接收器范围函数中工作

如何使用成员引用在 Kotlin 中创建属性的分层路径

我可以在 Kotlin 中使用接口类型作为构造函数参数吗

匹配在单词边界上包含特殊字符的变量字符串的正则表达式

如何从 kotlin 函数中 Select 正确的枚举值

如何使用 Kotlin KClass 属性 simpleName 生成空值

在 kotlin 中模拟伴随对象函数

AIDL 中的 Parcelize 注释:Incompatible types: Object cannot be converted to MyCustomObject

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

Kotlin-Java 互操作不能与可变参数一起使用

如何在 Spring WebFlux 的响应正文中流式传输二进制数据

Android 与 Kotlin - 如何使用 HttpUrlConnection

Android插件2.2.0-alpha1无法使用Kotlin编译

如何在Kotlin中使用ViewModelProviders

使用导航组件在BottomNavigationView中传递参数

在kotlin中初始化类变量的正确位置是什么

Kotlin 是否支持部分应用程序?