如何通过字节操作将代码从Java转换为Kotlin?

时间:2019-11-20 07:52:53

标签: java android kotlin translate

我想在Kotlin中转换此方法,但是我不知道要正确执行操作并具有正确的操作记忆的变量是什么:

public static UUID bytestoUUID(byte[] buf, int offset) {
    long lsb = 0;
    for (int i = 15; i >= 8; i--) {
        lsb = (lsb << 8) | (buf[i + offset] & 0xff);
    }

    long msb = 0;
    for (int i = 7; i >= 0; i--) {
        msb = (msb << 8) | (buf[i + offset] & 0xff);
    }

    return new UUID(msb, lsb);
}

您有正确的方法吗?谢谢

3 个答案:

答案 0 :(得分:1)

应该是

import java.util.*
import kotlin.experimental.and

 fun bytestoUUID(buf: ByteArray, offset: Int): UUID {
    var lsb: Long = 0
    for (i in 15 downTo 8) {
        lsb = lsb shl 8 or ((buf[i + offset] and 0xff.toByte()).toLong())
    }
    var msb: Long = 0
    for (i in 7 downTo 0) {
        msb = msb shl 8 or ((buf[i + offset] and 0xff.toByte()).toLong())
    }
    return UUID(msb, lsb)
}

答案 1 :(得分:0)

我终于找到了可以进行单元测试的好方法。

fun bytestoUUID(buf: ByteArray, offset: Int): UUID {
    var lsb: Long = 0
    for (i in 15 downTo 8) {
        lsb = lsb shl 8 or (buf[i + offset].toLong() and 0xff)
    }

    var msb: Long = 0
    for (i in 7 downTo 0) {
        msb = msb shl 8 or (buf[i + offset].toLong() and 0xff)
    }

    return UUID(msb, lsb)
}

答案 2 :(得分:0)

fun bytestoUUID(buf: ByteArray, offset: Int): UUID? {
    var lsb: Long = 0
    for (i in 15 downTo 8) {
        lsb = lsb shl 8 or (buf[i + offset] and 0xff)
    }
    var msb: Long = 0
    for (i in 7 downTo 0) {
        msb = msb shl 8 or (buf[i + offset] and 0xff)
    }
    return UUID(msb, lsb)
}