Как преобразовать метку времени UNIX в массив UInt8 в Kotlin?

<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>
1
задан adsalpha 28 March 2019 в 02:33
поделиться

2 ответа

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(""))
}
0
ответ дан Alexander Egger 28 March 2019 в 02:33
поделиться

Если вам нужно 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
ответ дан Aleksandr 28 March 2019 в 02:33
поделиться
Другие вопросы по тегам:

Похожие вопросы: