weibit | 38c42ed | 2014-10-09 19:03:54 -0700 | [diff] [blame^] | 1 | package org.onlab.util; |
| 2 | |
| 3 | public final class HexString { |
| 4 | |
| 5 | private HexString() { |
| 6 | |
| 7 | } |
| 8 | |
| 9 | /** |
| 10 | * Convert a string of bytes to a ':' separated hex string. |
| 11 | * |
| 12 | * @param bytes |
| 13 | * @return "0f:ca:fe:de:ad:be:ef" |
| 14 | */ |
| 15 | public static String toHexString(final byte[] bytes) { |
| 16 | int i; |
| 17 | StringBuilder ret = new StringBuilder(); |
| 18 | String tmp; |
| 19 | for (i = 0; i < bytes.length; i++) { |
| 20 | if (i > 0) { |
| 21 | ret.append(':'); |
| 22 | } |
| 23 | tmp = Integer.toHexString((bytes[i] & 0xff)); |
| 24 | if (tmp.length() == 1) { |
| 25 | ret.append('0'); |
| 26 | } |
| 27 | ret.append(tmp); |
| 28 | } |
| 29 | return ret.toString(); |
| 30 | } |
| 31 | |
| 32 | public static String toHexString(final long val, final int padTo) { |
| 33 | char[] arr = Long.toHexString(val).toCharArray(); |
| 34 | String ret = ""; |
| 35 | // prepend the right number of leading zeros |
| 36 | int i = 0; |
| 37 | for (; i < (padTo * 2 - arr.length); i++) { |
| 38 | ret += "0"; |
| 39 | if ((i % 2) != 0) { |
| 40 | ret += ":"; |
| 41 | } |
| 42 | } |
| 43 | for (int j = 0; j < arr.length; j++) { |
| 44 | ret += arr[j]; |
| 45 | if ((((i + j) % 2) != 0) && (j < (arr.length - 1))) { |
| 46 | ret += ":"; |
| 47 | } |
| 48 | } |
| 49 | return ret; |
| 50 | } |
| 51 | |
| 52 | public static String toHexString(final long val) { |
| 53 | return toHexString(val, 8); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Convert a string of hex values into a string of bytes. |
| 58 | * |
| 59 | * @param values |
| 60 | * "0f:ca:fe:de:ad:be:ef" |
| 61 | * @return [15, 5 ,2, 5, 17] |
| 62 | * @throws NumberFormatException |
| 63 | * If the string can not be parsed |
| 64 | */ |
| 65 | public static byte[] fromHexString(final String values) { |
| 66 | String[] octets = values.split(":"); |
| 67 | byte[] ret = new byte[octets.length]; |
| 68 | |
| 69 | for (int i = 0; i < octets.length; i++) { |
| 70 | if (octets[i].length() > 2) { |
| 71 | throw new NumberFormatException("Invalid octet length"); |
| 72 | } |
| 73 | ret[i] = Integer.valueOf(octets[i], 16).byteValue(); |
| 74 | } |
| 75 | return ret; |
| 76 | } |
| 77 | |
| 78 | public static long toLong(String value) { |
| 79 | String[] octets = value.split(":"); |
| 80 | if (octets.length > 8) { |
| 81 | throw new NumberFormatException("Input string is too big to fit in long: " + value); |
| 82 | } |
| 83 | long l = 0; |
| 84 | for (String octet: octets) { |
| 85 | if (octet.length() > 2) { |
| 86 | throw new NumberFormatException( |
| 87 | "Each colon-separated byte component must consist of 1 or 2 hex digits: " + value); |
| 88 | } |
| 89 | short s = Short.parseShort(octet, 16); |
| 90 | l = (l << 8) + s; |
| 91 | } |
| 92 | return l; |
| 93 | } |
| 94 | } |