Converting hex string and byte array by Scala Posted on September 14, 2012 by tmyymmt Converting hex string to byte array, and byte array to hex string by Scala. object HexBytesUtil { def hex2bytes(hex: String): Array[Byte] = { if(hex.contains(" ")){ hex.split(" ").map(Integer.parseInt(_, 16).toByte) } else if(hex.contains("-")){ hex.split("-").map(Integer.parseInt(_, 16).toByte) } else { hex.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)) } } Share this:Click to share on Twitter (Opens in new window)Click to share on Facebook (Opens in new window)Click to share on Tumblr (Opens in new window)Click to email a link to a friend (Opens in new window)
How about: str.replaceAll(“[^0-9A-Fa-f]”, “”).grouped(2).toArray map { Integer.parseInt(_, 16).toByte } ? Reply ↓
How about:
str.replaceAll(“[^0-9A-Fa-f]”, “”).grouped(2).toArray map { Integer.parseInt(_, 16).toByte }
?