Skip to content

Instantly share code, notes, and snippets.

@jodersky
Created February 17, 2022 18:17
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 jodersky/3756640afadf49fbcfbb9340f608063b to your computer and use it in GitHub Desktop.
Save jodersky/3756640afadf49fbcfbb9340f608063b to your computer and use it in GitHub Desktop.
def hexify(bytes: Array[Byte]): String = {
val builder = new StringBuilder
for (i <- 0 until bytes.length) {
val b = bytes(i)
val upperNibble = (b >>> 4) & 0x0f
val lowerNibble = b & 0x0f
builder += Character.forDigit(upperNibble, 16)
builder += Character.forDigit(lowerNibble, 16)
}
builder.result()
}
def unhexify(str: String): Array[Byte] = {
val bytes = new Array[Byte](str.length / 2)
for (i <- 0 until str.length / 2) {
val upperNibble = Character.digit(str.charAt(i * 2), 16)
val lowerNibble = Character.digit(str.charAt(i * 2 + 1), 16)
bytes(i) = ((upperNibble << 4) | lowerNibble).toByte
}
bytes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment