byte array to HEX converter
authorSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Wed, 29 May 2013 15:04:19 +0000 (18:04 +0300)
committerSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Wed, 29 May 2013 15:04:19 +0000 (18:04 +0300)
src/main/java/eu/svjatoslav/commons/data/HexConverter.java [new file with mode: 0644]
src/test/java/eu/svjatoslav/commons/data/HexConverterTest.java [new file with mode: 0644]

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 (file)
index 0000000..52b16f4
--- /dev/null
@@ -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 (file)
index 0000000..2525f9b
--- /dev/null
@@ -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);
+
+       }
+}