Skip to content

Instantly share code, notes, and snippets.

@fabiomsr
Last active April 24, 2024 08:41
Show Gist options
  • Star 65 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save fabiomsr/845664a9c7e92bafb6fb0ca70d4e44fd to your computer and use it in GitHub Desktop.
Save fabiomsr/845664a9c7e92bafb6fb0ca70d4e44fd to your computer and use it in GitHub Desktop.
ByteArray and String extension to add hexadecimal methods in Kotlin
private val HEX_CHARS = "0123456789ABCDEF".toCharArray()
fun ByteArray.toHex() : String{
val result = StringBuffer()
forEach {
val octet = it.toInt()
val firstIndex = (octet and 0xF0).ushr(4)
val secondIndex = octet and 0x0F
result.append(HEX_CHARS[firstIndex])
result.append(HEX_CHARS[secondIndex])
}
return result.toString()
}
private val HEX_CHARS = "0123456789ABCDEF"
fun String.hexStringToByteArray() : ByteArray {
val result = ByteArray(length / 2)
for (i in 0 until length step 2) {
val firstIndex = HEX_CHARS.indexOf(this[i]);
val secondIndex = HEX_CHARS.indexOf(this[i + 1]);
val octet = firstIndex.shl(4).or(secondIndex)
result.set(i.shr(1), octet.toByte())
}
return result
}
@todorus
Copy link

todorus commented Mar 5, 2021

For people commenting alternatives to the gist, bear in mind that the gist is in Kotlin. The API does not have String.format, as this is from the Kotlin JVM lib. The posted examples won't work in Kotlin Native.

Copy link

ghost commented Jul 29, 2021

For people commenting alternatives to the gist, bear in mind that the gist is in Kotlin. The API does not have String.format, as this is from the Kotlin JVM lib. The posted examples won't work in Kotlin Native.

source.joinToString("") { it.toInt().and(0xff).toString(16).padStart(2, '0') }

works with Kotlin/Native at least for the targets JVM, Android, iOS & macOS as expected

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment