简体   繁体   English

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

[英]How to translate code with byte operation from Java to Kotlin?

I would like to translate this method in Kotlin but I do not know what are the variables to cast to do things correctly and have the right operations memories:我想在 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);
}

Do you have the right way?你有正确的方法吗? Thank you谢谢

It should be它应该是

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

I finally found the good cast to do for the unit tests to work.我终于找到了让单元测试工作的好演员。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM