DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Scala Code To Convert To/from HEX Encoded Values
// These methods convert to/from a Hex encoded String from/to a byte array
def hex2Bytes( hex: String ): Array[Byte] = {
(for { i <- 0 to hex.length-1 by 2 if i > 0 || !hex.startsWith( "0x" )}
yield hex.substring( i, i+2 ))
.map( Integer.parseInt( _, 16 ).toByte ).toArray
}
def bytes2Hex( bytes: Array[Byte] ): String = {
def cvtByte( b: Byte ): String = {
(if (( b & 0xff ) < 0x10 ) "0" else "" ) + Long.toString( b & 0xff, 16 )
}
"0x" + bytes.map( cvtByte( _ )).mkString.toUpperCase
}





