我在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);
}
我想将此代码转换为kotlin。自动转换给出了下一个结果:
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)
}
但kotlin中的字节类型没有函数ushr
。我已经尝试将v转换为Int并移动此值并将其再次转换为Byte,如(v.toInt().ushr(4) as Byte).toInt()
。但它给出了错误的结果。将此函数转换为kotlin的正确方法是什么。
答案 0 :(得分:2)
您可以将bytes[j]
转换为integer
,然后代码可以运行:
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"))))
}
如果你运行这个,你就可以登上控制台了:
68656C6C6F5F776F726C64