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);
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
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.
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"))))
}
Run Code Online (Sandbox Code Playgroud)
If you run this you get on the console this:
68656C6C6F5F776F726C64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5280 次 |
| 最近记录: |