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

Make it happen: rapid app development on Kubernetes as a managed service.

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

Tutorial: WordPress as distributed microservices on Kubernetes.


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}