Problem with migration to Kotlin (toHexString method)

I get an exception “java.lang.ArrayIndexOutOfBoundsException” in one method if I use a Kotlin syntax, but when I use Java I don’t have any exception.

The method on Java:
private static final char HEX = “0123456789ABCDEF”.toCharArray();

public static String toHexString(byte bytes) {
if (bytes.length == 0) {
return “”;
}
char chars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
int c = bytes[i] & 0xFF;
chars[i * 2] = HEX[c >>> 4];
chars[i * 2 + 1] = HEX[c & 0x0F];
}
return new String(chars).toLowerCase();
}

The method on Kotlin (as an extension):
fun ByteArray?.toHexString(): String {
this?.let {

    val hexArray = "0123456789ABCDEF".toCharArray()

    val hexChars = CharArray(it.size * 2)
    for (j in it.indices) {
        val v = (it[j] and 0xFF.toByte()).toInt()

        hexChars[j * 2] = hexArray[v ushr 4]
        hexChars[j * 2 + 1] = hexArray[v and 0x0F]
    }
    return String(hexChars)

}
return ""

}

Where did I make a mistake? Please help me.

bytes[i] & 0xFF operates on Int, instead it[j] and 0xFF.toByte() operates on Byte.
The equivalent code is val v = get(j).toInt() and 0xFF

1 Like

@fvasco, thanks!
Now it works fine