Skip to content

Instantly share code, notes, and snippets.

@tmyymmt
Created September 15, 2012 09:37
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save tmyymmt/3727124 to your computer and use it in GitHub Desktop.
Save tmyymmt/3727124 to your computer and use it in GitHub Desktop.
hex2bytes and bytes2hex fixed
object HexBytesUtil {
def hex2bytes(hex: String): Array[Byte] = {
hex.replaceAll("[^0-9A-Fa-f]", "").sliding(2, 2).toArray.map(Integer.parseInt(_, 16).toByte)
}
def bytes2hex(bytes: Array[Byte], sep: Option[String] = None): String = {
sep match {
case None => bytes.map("%02x".format(_)).mkString
case _ => bytes.map("%02x".format(_)).mkString(sep.get)
}
// bytes.foreach(println)
}
def example {
val data = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21 21"
val bytes = hex2bytes(data)
println(bytes2hex(bytes, Option(" ")))
val data2 = "48-65-6C-6C-6F-20-57-6F-72-6C-64-21-21"
val bytes2 = hex2bytes(data2)
println(bytes2hex(bytes2, Option("-")))
val data3 = "48656C6C6F20576F726C642121"
val bytes3 = hex2bytes(data3)
println(bytes2hex(bytes3))
}
}
@lemonxah
Copy link

lemonxah commented Mar 2, 2015

def bytes2Hex(bytes: Array[Byte], sep: Option[String] = None): String = {
bytes.map("%02x".format(_)) mkString (sep match {
case None => ""
case Some(s) => s
})
}

@kushti
Copy link

kushti commented Mar 9, 2015

def bytes2hex(bytes: Array[Byte], sep: Option[String] = None): String =
bytes.map("%02x".format(_)).mkString(sep.getOrElse(""))

@alxmrtn
Copy link

alxmrtn commented May 15, 2015

def bytes2hex(bytes: Array[Byte], sep: String = ""): String = bytes.map("%02x".format(_)).mkString(sep)

@jpzk
Copy link

jpzk commented Oct 18, 2018

def hex2X[T](hex: String, f: BigInt => T) = f(BigInt(hex.drop(2), 16))
def hex2Bytes(hex: String): Array[Byte] = hex2X(hex, _.toByteArray)
works for e.g. 0xEEAA prepended 0x

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