Groovy Goodness: Converting Byte Array to Hex String
Join the DZone community and get the full member experience.
Join For FreeTo convert a byte[]
array to a String
we can simply use the new String(byte[])
constructor. But if the array contains non-printable bytes we don't get a good representation. In Groovy we can use the method encodeHex()
to transform a byte[]
array to a hex String
value. The byte
elements are converted to their hexadecimal equivalents.
final byte[] printable = [109, 114, 104, 97, 107, 105] // array with non-printable bytes 6, 27 (ACK, ESC) final byte[] nonprintable = [109, 114, 6, 27, 104, 97, 107, 105] assert new String(printable) == 'mrhaki' assert new String(nonprintable) != 'mr haki' // encodeHex() returns a Writable final Writable printableHex = printable.encodeHex() assert printableHex.toString() == '6d7268616b69' final nonprintableHex = nonprintable.encodeHex().toString() assert nonprintableHex == '6d72061b68616b69' // Convert back assert nonprintableHex.decodeHex() == nonprintable
Code written with Groovy 2.2.1
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments