-
-
Save arifNislam/4f7766df1f490623eb8fa4400ae3af4c to your computer and use it in GitHub Desktop.
ByteArray and String extension to add hexadecimal methods in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment