blob: 14cd41941f07674786f6ce3e77d423a589a285d3 [file] [log] [blame]
Jonathan Hart6df90172014-04-03 10:13:11 -07001package net.onrc.onos.core.datastore.utils;
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -08002
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,
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070020 final String sep) {
21 return toHexStringBuffer(bytes, sep, new StringBuffer());
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080022 }
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 HIGUCHI826b4a42014-03-24 13:10:33 -070035 final String sep, final StringBuffer buf) {
36 if (bytes == null) {
37 return buf;
38 }
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080039
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070040 ByteBuffer wrap = ByteBuffer.wrap(bytes);
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080041
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070042 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 }
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080050
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070051 return buf;
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080052 }
53}