jw
06/19/2017, 1:39 PMjw
06/19/2017, 1:40 PMmarcinmoskala
06/19/2017, 2:05 PMprivate val hexArray = CharArray(16) { if (it < 10) '0' + it else 'a' + (it - 10) }
fun ByteArray.toHexString(): String {
val builder = StringBuilder(size * 2)
for (byte in this) {
val v = byte.toInt() and 0xFF
builder.append(hexArray[v.ushr(4)])
builder.append(hexArray[v and 0x0F])
}
return builder.toString()
}
Implementation a bit slower, but multiplatformmarcinmoskala
06/19/2017, 2:10 PMmarcinmoskala
06/19/2017, 2:11 PMjw
06/19/2017, 2:12 PMmarcinmoskala
06/19/2017, 2:32 PMmg6maciej
06/19/2017, 2:43 PMBigInteger
almost works, but it eats leading zeros. Beware!mg6maciej
06/19/2017, 2:58 PMbyteArrayFromHexString()
toplevel function?marcinmoskala
06/19/2017, 3:11 PMkirillrakhman
06/19/2017, 4:30 PMByteArray
, oh wait...bamdmux
06/20/2017, 5:57 AMbamdmux
06/20/2017, 5:57 AMprivate val CHARS = "0123456789ABCDEF".toList().toCharArray()
fun Byte.toHex() = toInt().let { "${CHARS[it.shr(4).and(0x0F)]}${CHARS[it.and(0x0F)]}" }
fun List<Byte>.toHexString(sep: String = "") = map(Byte::toHex).joinToString(separator = sep)
fun String.hexList(): List<Byte> = with(filter { it != ':' }.toUpperCase()) {
if (length % 2 != 0) throw NumberFormatException("Odd number of characters: $length")
if (!all { it in CHARS }) throw NumberFormatException("Invalid characters: ${this@hexList}")
ByteArray(length / 2).mapIndexed { i, _ ->
((CHARS.indexOf(this[i * 2]).shl(4)) + (CHARS.indexOf(this[i * 2 + 1]))).toByte()
}
}
bamdmux
06/20/2017, 5:59 AMfun ByteArray.toHexString(sep: String = "") = toList().toHexString(sep)
mg6maciej
06/20/2017, 7:45 AMCompanion
on all classes, Java ones or not. #language-proposalsjw
06/20/2017, 2:11 PMjw
06/20/2017, 2:13 PMCharArray
jw
06/20/2017, 2:14 PMByteArray
to List<Byte>
just to transform it to another representation is really wastefuljw
06/20/2017, 2:14 PMjw
06/20/2017, 2:14 PMilya.gorbunov
06/20/2017, 2:15 PMdamian
06/20/2017, 3:05 PMWeakReference
something that can be supported in the stdlib directly, as a mapped type like Comparator
, List
, etc?kevinmost
06/20/2017, 3:13 PMdamian
06/20/2017, 3:15 PMkz
06/20/2017, 3:25 PMnatpryce
06/22/2017, 12:36 PMnatpryce
06/22/2017, 1:21 PMnatpryce
06/22/2017, 1:21 PMtypealias myproject.Random = java.util.Random
natpryce
06/22/2017, 1:22 PMnatpryce
06/22/2017, 1:22 PMmyproject.Random
in the code that is compiled for JavaScript