Search code examples
timekotlinbyteunix-timestampuint

How to convert the a UNIX timestamp to an array of UInt8 in Kotlin?


I need to convert a UNIX timestamp to a ByteArray in Kotlin. The problem is, when I do that using the code below, I get a result like C1F38E05 (hex) which is way above the current epoch time.

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()

What is the right way to do it?


Solution

  • If you need a 32 bit value, you need to convert time to seconds.

    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()