Yuta HIGUCHI | c9d06ef | 2014-01-31 15:55:12 -0800 | [diff] [blame] | 1 | package net.onrc.onos.datastore.utils; |
| 2 | |
| 3 | import java.nio.ByteBuffer; |
| 4 | |
| 5 | public class ByteArrayUtil { |
| 6 | |
Yuta HIGUCHI | 66ca1bf | 2014-03-12 18:34:09 -0700 | [diff] [blame] | 7 | // 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 HIGUCHI | c9d06ef | 2014-01-31 15:55:12 -0800 | [diff] [blame] | 19 | public static StringBuffer toHexStringBuffer(final byte[] bytes, |
| 20 | final String sep) { |
| 21 | return toHexStringBuffer(bytes, sep, new StringBuffer()); |
| 22 | } |
| 23 | |
Yuta HIGUCHI | 66ca1bf | 2014-03-12 18:34:09 -0700 | [diff] [blame] | 24 | /** |
| 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 HIGUCHI | c9d06ef | 2014-01-31 15:55:12 -0800 | [diff] [blame] | 34 | public static StringBuffer toHexStringBuffer(final byte[] bytes, |
Yuta HIGUCHI | 66ca1bf | 2014-03-12 18:34:09 -0700 | [diff] [blame] | 35 | final String sep, final StringBuffer buf) { |
Yuta HIGUCHI | c9d06ef | 2014-01-31 15:55:12 -0800 | [diff] [blame] | 36 | 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 | } |