Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Java bitwise "and" operator over to Kotlin

I have a an array of bytes I'm calculating a checksum for in Java. And I'm trying to convert it to Kotlin. But the problem is that I am getting different values when calculating the -128 & 0xff in Java than it's equivalent in Kotlin. When passing in the -128, when I make the calculation in Java, it gives me a positive 128, but when I run it in Kotlin, it gives me a -128.

public class Bytes {

    public static byte[] getByteArray() {
        return new byte [] {-128};
    }

    public static int getJavaChecksum() {
        int checksum = 0;

        for (Byte b : getByteArray()) {
            checksum += (b & 0xff);
        }

        return checksum;
    }
}

This is my Kotlin code. I'm calling into the above bytes class to get the "byte array" I'm working with. So both pieces are running on the same input.

fun getKotlinChecksum(array: ByteArray): Byte {
    var checksum = 0
    for (b in array) {
        checksum += (b and 0xFF.toByte())
    }
    return checksum.toByte()
}

fun main(args: Array<String>) {

    println(Bytes.getJavaChecksum())
    print(getKotlinChecksum(Bytes.getByteArray()))
}

The Java code is from a legacy code base that uses I2C to send over these bytes to a microcontroller. Is the Java just wrong? Or is there a way that I can get the 128 in the Kotlin code?

like image 409
Rafa Avatar asked Oct 17 '22 10:10

Rafa


1 Answers

Returning a Byte means the function cannot return 128 no matter what, so that needs to be Int. The Java checksum does a "full" sum, not just the lowest byte of the sum. Similarly the bitwise AND cannot be done on bytes, that is useless, the sign extension (the AND with 0xFF is to remove the extended sign bits) would still happen. Then it could be written as a loop, Java style, but in Kotlin it probably makes more sense to write something like this:

fun getKotlinChecksum(array: ByteArray): Int {
    return array.map({ it.toInt() and 0xFF }).sum()
}
like image 170
harold Avatar answered Oct 30 '22 13:10

harold