【问题标题】:How to cast Int to Char in Kotlin如何在 Kotlin 中将 Int 转换为 Char
【发布时间】:2021-06-04 09:17:28
【问题描述】:

使用 Java 原语很容易将字符代码转换为符号

int i = 65;
char c = (char) i; // 'A'

如何用 Kotlin 做同样的事情?

【问题讨论】:

    标签: kotlin casting


    【解决方案1】:

    使用int.toChar() 函数来完成。

    【讨论】:

    • 但它会将 int 截断为 16 位,所以 128104.toChar() 没有给出想要的结果 (?)
    • @fdermishin 然后使用 Long,而不是 Int
    • @david.barkhuizen 那行不通。 Returns the Char with the numeric value equal to this number, truncated to 16 bits if appropriate.kotlinlang.org/api/latest/jvm/stdlib/kotlin/-long/to-char.html
    • @fdermishin 同意。请查看我的完整答案以获得正确的解决方案。
    【解决方案2】:

    首先使用 ByteBuffer 将 Int 转换为 ByteArray(具有正确的字节顺序),然​​后使用适当的 String 构造函数。

    import java.nio.ByteBuffer
    import java.nio.ByteOrder
    import java.nio.charset.Charset
    
    fun intToByteArray(n: Int, byteOrder: ByteOrder) =
        ByteBuffer.allocate(4).order(byteOrder).putInt(n).array()
    
    fun byteArrayToUnicode(ba: ByteArray, charSet: Charset) =
        String(ba, charSet)
    
    fun intToUniCode(n: Int, byteOrder: ByteOrder, charSet: Charset) =
        byteArrayToUnicode(intToByteArray(n, byteOrder), charSet)
    
    fun test() {
        val charSet = Charset.forName("UTF-32BE")
        val n = 0x000000f7 // division sign (U+00F7)
        val s = intToUniCode(n, ByteOrder.BIG_ENDIAN, charSet)
        println(s)
    }
    

    【讨论】:

    • 从技术上讲,此解决方案适用于使用 Kotlin 的 Java,不适用于本机 Kotlin。
    猜你喜欢
    • 2017-03-21
    • 2011-04-09
    • 2018-05-15
    • 2012-06-02
    • 2015-04-07
    • 1970-01-01
    • 2017-11-21
    • 2021-08-15
    • 2011-07-10
    相关资源
    最近更新 更多