Reputation: 857
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 :
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
Upvotes: 0
Views: 199
Reputation: 29
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)
}
Upvotes: 0
Reputation: 857
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)
}
Upvotes: 0
Reputation: 13348
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)
}
Upvotes: 1