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)) }
0 comments:
Post a Comment