blob: c13d7ea7e4d09fd1eeb72d1d5519106f68d4c7d9 [file] [log] [blame]
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -08001package net.onrc.onos.datastore.utils;
2
3import java.nio.ByteBuffer;
4
5public class ByteArrayUtil {
6
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -07007 // Suppresses default constructor, ensuring non-instantiability.
8 private ByteArrayUtil() {}
9
10 /**
11 * Returns a StringBuffer with each byte in {@code bytes}
12 * converted to a String with {@link Integer#toHexString(int)},
13 * separated by {@code sep}.
14 *
15 * @param bytes byte array to convert
16 * @param sep separator between each bytes
17 * @return {@code bytes} converted to a StringBuffer
18 */
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080019 public static StringBuffer toHexStringBuffer(final byte[] bytes,
20 final String sep) {
21 return toHexStringBuffer(bytes, sep, new StringBuffer());
22 }
23
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -070024 /**
25 * Returns a StringBuffer with each byte in {@code bytes}
26 * converted to a String with {@link Integer#toHexString(int)},
27 * separated by {@code sep}.
28 *
29 * @param bytes byte array to convert
30 * @param sep separator between each bytes
31 * @param buf StringBuffer to append to.
32 * @return {@code buf}
33 */
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080034 public static StringBuffer toHexStringBuffer(final byte[] bytes,
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -070035 final String sep, final StringBuffer buf) {
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080036 if (bytes == null) {
37 return buf;
38 }
39
40 ByteBuffer wrap = ByteBuffer.wrap(bytes);
41
42 boolean hasWritten = false;
43 while (wrap.hasRemaining()) {
44 if (hasWritten) {
45 buf.append(sep);
46 }
47 buf.append(Integer.toHexString(wrap.get()));
48 hasWritten = true;
49 }
50
51 return buf;
52 }
53}