Over a million developers have joined DZone.

Groovy Goodness: Converting Byte Array to Hex String

DZone 's Guide to

Groovy Goodness: Converting Byte Array to Hex String

· Java Zone ·
Free Resource

To 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 byteelements 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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}