From: Svjatoslav Agejenko Date: Wed, 29 May 2013 15:04:19 +0000 (+0300) Subject: byte array to HEX converter X-Git-Tag: svjatoslavcommons-1.8~144 X-Git-Url: http://www2.svjatoslav.eu/gitweb/?a=commitdiff_plain;h=fff91edf05201dea6191c450eded1b711baa5493;p=svjatoslav_commons.git byte array to HEX converter --- diff --git a/src/main/java/eu/svjatoslav/commons/data/HexConverter.java b/src/main/java/eu/svjatoslav/commons/data/HexConverter.java new file mode 100644 index 0000000..52b16f4 --- /dev/null +++ b/src/main/java/eu/svjatoslav/commons/data/HexConverter.java @@ -0,0 +1,21 @@ +package eu.svjatoslav.commons.data; + +public class HexConverter { + + static final String hexCodes = "0123456789ABCDEF"; + + public static String byteArrayToHex(final byte[] raw) { + + if (raw == null) + return null; + + final StringBuilder result = new StringBuilder(2 * raw.length); + + for (final byte b : raw) + result.append(hexCodes.charAt((b & 0xF0) >> 4)).append( + hexCodes.charAt((b & 0x0F))); + + return result.toString(); + } + +} diff --git a/src/test/java/eu/svjatoslav/commons/data/HexConverterTest.java b/src/test/java/eu/svjatoslav/commons/data/HexConverterTest.java new file mode 100644 index 0000000..2525f9b --- /dev/null +++ b/src/test/java/eu/svjatoslav/commons/data/HexConverterTest.java @@ -0,0 +1,18 @@ +package eu.svjatoslav.commons.data; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HexConverterTest { + + @Test + public void test() { + + final String string = HexConverter.byteArrayToHex(new byte[] { 1, 2, + (byte) 255 }); + + assertEquals("0102FF", string); + + } +}