Simple Hex String to ASCII Function for Scala.

by 10/08/2012 03:39:00 PM 0 comments
This a simple function for converting a HEX string to an ASCII representation using Scala. There's nothing fancy here, I'm just making a note of it as I need it occasionally.
def toAscii(hex: String) = {
  require(hex.size % 2 == 0, 
    "Hex must have an even number of characters. You had " + hex.size)
  val sb = new StringBuilder
  for (i <- 0 until hex.size by 2) {
    val str = hex.substring(i, i + 2)
    sb.append(Integer.parseInt(str, 16).toChar)
  }
  sb.toString
}
Here's an example of it's usage:
scala> val d = toAscii("20202D3238312E313320202D35392E34363220202031372E313331202020323636342E350D0A49")
d: java.lang.String = 
"  -281.13  -59.462   17.131   2664.5
I"
And yes, I know it's not written in a functional style. I wrote a different version using hex.init.zip(hex.tail).blah.blah.blah. But it was just non-sensical to read. If you have an easy-to-understand-functional version, I'd love to see it (Thanks!)

UPDATE
Here's another method that just uses Java's built-in functions:
def toAscii(hex: String) = {
  import javax.xml.bind.DatatypeConverter
  new String(DatatypeConverter.parseHexBinary(hex))
}

Brian Schlining

Developer

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

0 comments: