如何将字节操作的代码从 Java 翻译成 Kotlin?
How to translate code with byte operation from Java to Kotlin?
我想在 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);
}
你有正确的方法吗?谢谢
应该是
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)
}
我终于找到了让单元测试起作用的好方法。
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)
}
我想在 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);
}
你有正确的方法吗?谢谢
应该是
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)
}
我终于找到了让单元测试起作用的好方法。
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)
}