blob: 96d00485828f0b613b270a967a5664b95dc4c7b2 [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
Ray Milkey1584ec82014-04-10 11:58:30 -07005public final class ByteArrayUtil {
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -08006
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -07007 // Suppresses default constructor, ensuring non-instantiability.
Ray Milkey269ffb92014-04-03 14:43:30 -07008 private ByteArrayUtil() {
9 }
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -070010
11 /**
12 * Returns a StringBuffer with each byte in {@code bytes}
13 * converted to a String with {@link Integer#toHexString(int)},
14 * separated by {@code sep}.
15 *
16 * @param bytes byte array to convert
Ray Milkey269ffb92014-04-03 14:43:30 -070017 * @param sep separator between each bytes
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -070018 * @return {@code bytes} converted to a StringBuffer
19 */
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080020 public static StringBuffer toHexStringBuffer(final byte[] bytes,
Ray Milkey269ffb92014-04-03 14:43:30 -070021 final String sep) {
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070022 return toHexStringBuffer(bytes, sep, new StringBuffer());
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080023 }
24
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -070025 /**
26 * Returns a StringBuffer with each byte in {@code bytes}
27 * converted to a String with {@link Integer#toHexString(int)},
28 * separated by {@code sep}.
29 *
30 * @param bytes byte array to convert
Ray Milkey269ffb92014-04-03 14:43:30 -070031 * @param sep separator between each bytes
32 * @param buf StringBuffer to append to.
Yuta HIGUCHI66ca1bf2014-03-12 18:34:09 -070033 * @return {@code buf}
34 */
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080035 public static StringBuffer toHexStringBuffer(final byte[] bytes,
Ray Milkey269ffb92014-04-03 14:43:30 -070036 final String sep, final StringBuffer buf) {
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070037 if (bytes == null) {
38 return buf;
39 }
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080040
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070041 ByteBuffer wrap = ByteBuffer.wrap(bytes);
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080042
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070043 boolean hasWritten = false;
44 while (wrap.hasRemaining()) {
45 if (hasWritten) {
46 buf.append(sep);
47 }
48 buf.append(Integer.toHexString(wrap.get()));
49 hasWritten = true;
50 }
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080051
Yuta HIGUCHI826b4a42014-03-24 13:10:33 -070052 return buf;
Yuta HIGUCHIc9d06ef2014-01-31 15:55:12 -080053 }
54}