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

标签 time kotlin byte unix-timestamp uint

我需要在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()

正确的做法是什么?

最佳答案

如果需要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()

关于time - 如何在Kotlin中将UNIX时间戳转换为UInt8数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389334/

相关文章:

java - SimpleDateFormat - 解析日期时出现奇怪的结果

php - 搜索时间范围在 php/mysql 中不起作用

php - 获取用户时间和服务器时间之间的时差?

android - 调用 Fragment 构造函数导致异常,kotlin?

rust - 按位运算,将u32与字节数组进行比较

php - 在 PHP 中将多个日期转换为 Unix 时间

android - 使用 repeatOnLifeCycle 从 UI 中的 Flow 收集

android - 通过形状资源文件设置圆角的 ConstraintLayout 不起作用

java - 图像名称和扩展名

java - 如何将 1 和 0 转换为字符串?