Skip to content

Instantly share code, notes, and snippets.

@shafty023
Last active August 24, 2022 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shafty023/b04428270b96fee3afcfc2042cbefd92 to your computer and use it in GitHub Desktop.
Save shafty023/b04428270b96fee3afcfc2042cbefd92 to your computer and use it in GitHub Desktop.
Convert a ByteArray to Hex encoded String
private val HEX_CHARS = "0123456789ABCDEF".toCharArray()
/**
* Extension function that converts a ByteArray to a hex encoded CharArray.
*/
fun ByteArray.toHex(): CharArray {
val result = StringBuilder()
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().toCharArray()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment