I have next code in java:
private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
I want to convert this code to kotlin. Autoconverting gave next result:
fun bytesToHex(bytes: ByteArray): String {
val hexChars = CharArray(bytes.size * 2)
for (j in bytes.indices) {
val v = bytes[j] and 0xFF
hexChars[j * 2] = HEX_ARRAY[v.ushr(4)]
hexChars[j * 2 + 1] = HEX_ARRAY[v and 0x0F]
}
return String(hexChars)
}
but there is no function ushr
for type Byte in kotlin. I've tried convert v to Int and shift this value and convert it again to Byte like (v.toInt().ushr(4) as Byte).toInt()
. But it gives wrong result. What is the correct way to convert this function into kotlin.
A byte is an 8-bit number in Kotlin. This type is mentioned explicitly. A byte value ranges from -128 to 127. In JVM, the characteristics of this "Byte" variable is derived from the characteristics of primitive type byte of Java which has a non-nullable default value.
Bitwise and bit shift operators are used on only two integral types ( Int and Long ) to perform bit-level operations. To peform these operations, Kotlin provides 7 functions using infix notation.
To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.
The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.
You can convert bytes[j]
to an integer
and then the code works:
private val HEX_ARRAY = "0123456789ABCDEF".toCharArray()
fun bytesToHex(bytes: ByteArray): String {
val hexChars = CharArray(bytes.size * 2)
for (j in bytes.indices) {
val v = bytes[j].toInt() and 0xFF // Here is the conversion
hexChars[j * 2] = HEX_ARRAY[v.ushr(4)]
hexChars[j * 2 + 1] = HEX_ARRAY[v and 0x0F]
}
return String(hexChars)
}
fun main(args: Array<String>) {
val s = "hello_world"
println(bytesToHex(s.toByteArray(Charset.forName("UTF-8"))))
}
If you run this you get on the console this:
68656C6C6F5F776F726C64
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With