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

Douglas has posted 12 posts at DZone. View Full User Profile

Scala Code To Convert To/from HEX Encoded Values

10.04.2009
| 10627 views |
  • submit to reddit
        // 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
    }