From fff91edf05201dea6191c450eded1b711baa5493 Mon Sep 17 00:00:00 2001 From: Svjatoslav Agejenko Date: Wed, 29 May 2013 18:04:19 +0300 Subject: [PATCH] byte array to HEX converter --- .../svjatoslav/commons/data/HexConverter.java | 21 +++++++++++++++++++ .../commons/data/HexConverterTest.java | 18 ++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/main/java/eu/svjatoslav/commons/data/HexConverter.java create mode 100644 src/test/java/eu/svjatoslav/commons/data/HexConverterTest.java 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); + + } +} -- 2.20.1