如何在Kotlin中将UNIX时间戳转换为UInt8数组?

问题描述 投票:1回答:2

我需要在Kotlin中将UNIX时间戳转换为ByteArray。问题是,当我使用下面的代码执行此操作时,我得到的结果类似于C1F38E05(hex),它高于当前的纪元时间。

internal fun Int.toByteArray(): ByteArray {
    return byteArrayOf(
            this.ushr(24).toByte(),
            this.ushr(16).toByte(),
            this.ushr(8).toByte(),
            this.toByte()
    )
}

val timeUTC = System.currentTimeMillis().toInt().toByteArray()

做正确的方法是什么?

time kotlin byte unix-timestamp uint
2个回答
1
投票

如果需要32位值,则需要将时间转换为秒。

fun Int.toByteArray() = byteArrayOf(
    this.toByte(),
    (this ushr 8).toByte(),
    (this ushr 16).toByte(),
    (this ushr 24).toByte()
)

val timeUTC = (System.currentTimeMillis() / 1000).toInt().toByteArray()

0
投票

System.currentTimeMillis()返回Long所以toByteArray必须像Long一样实现:

fun Long.toByteArray(): ByteArray {                     
    val result = ByteArray(8)                           
    result[7] = (this and 0xFF).toByte()                
    result[6] = ((this ushr 8) and 0xFF).toByte()       
    result[5] = ((this ushr 16) and 0xFF).toByte()      
    result[4] = ((this ushr 24) and 0xFF).toByte()      
    result[3] = ((this ushr 32) and 0xFF).toByte()      
    result[2] = ((this ushr 40) and 0xFF).toByte()      
    result[1] = ((this ushr 48) and 0xFF).toByte()      
    result[0] = ((this ushr 56) and 0xFF).toByte()      
    return result                                       
}    

如果你需要这个用于无符号字节,请使用:

fun Long.toByteArray(): UByteArray {
    val result = UByteArray(8)
    result[7] = (this and 0xFF).toUByte()
    result[6] = ((this ushr 8) and 0xFF).toUByte()
    result[5] = ((this ushr 16) and 0xFF).toUByte()
    result[4] = ((this ushr 24) and 0xFF).toUByte()
    result[3] = ((this ushr 32) and 0xFF).toUByte()
    result[2] = ((this ushr 40) and 0xFF).toUByte()
    result[1] = ((this ushr 48) and 0xFF).toUByte()
    result[0] = ((this ushr 56) and 0xFF).toUByte()
    return result
}

这可以像下面的示例一样使用:

fun main() {
    val timeUTC = System.currentTimeMillis().toByteArray()    
    println(timeUTC.map { byte -> byte.toString(16).toUpperCase() }.joinToString(""))
}
© www.soinside.com 2019 - 2024. All rights reserved.