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