Added possibility to decode HEX strings without separator
Change-Id: I6e11ad2a3dc4e39b148a740d5f19d80705f78b48
(cherry picked from commit 6eaa33ab046dde1ee79ce976457f1fb7f0a85b5f)
diff --git a/utils/misc/src/main/java/org/onlab/util/HexString.java b/utils/misc/src/main/java/org/onlab/util/HexString.java
index 07cf927..b04dd04 100644
--- a/utils/misc/src/main/java/org/onlab/util/HexString.java
+++ b/utils/misc/src/main/java/org/onlab/util/HexString.java
@@ -109,7 +109,25 @@
* @throws NumberFormatException if input hex string cannot be parsed
*/
public static byte[] fromHexString(final String values) {
- String[] octets = values.split(":");
+ return fromHexString(values, ":");
+ }
+
+ /**
+ * Convert a hex-string with arbitrary separator to byte array.
+ * If separator is the empty string or null, then no separator will be considered.
+ *
+ * @param values hex string to be converted
+ * @return converted byte array
+ * @throws NumberFormatException if input hex string cannot be parsed
+ */
+ public static byte[] fromHexString(final String values, String separator) {
+ String regexSeparator;
+ if (separator == null || separator.length() == 0) {
+ regexSeparator = "(?<=\\G.{2})"; // Split string into several two character strings
+ } else {
+ regexSeparator = separator;
+ }
+ String[] octets = values.split(regexSeparator);
byte[] ret = new byte[octets.length];
for (int i = 0; i < octets.length; i++) {
diff --git a/utils/misc/src/test/java/org/onlab/util/HexStringTest.java b/utils/misc/src/test/java/org/onlab/util/HexStringTest.java
index b288718..250c783 100644
--- a/utils/misc/src/test/java/org/onlab/util/HexStringTest.java
+++ b/utils/misc/src/test/java/org/onlab/util/HexStringTest.java
@@ -21,6 +21,9 @@
import junit.framework.TestCase;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+
import static org.junit.Assert.fail;
/**
@@ -55,6 +58,22 @@
}
@Test
+ public void testFromHexString() {
+ String dpidStr = "3e:1f:01:fc:72:8c:63:31";
+ String dpidStrNoSep = "3e1f01fc728c6331";
+ long valid = 0x3e1f01fc728c6331L;
+ byte[] validBytes = ByteBuffer.allocate(Long.BYTES).putLong(valid).array();
+ byte[] testBytes = HexString.fromHexString(dpidStr);
+ byte[] testBytesNoSep = HexString.fromHexString(dpidStrNoSep, null);
+ byte[] testBytesUCase = HexString.fromHexString(dpidStr.toUpperCase());
+ byte[] testBytesUCaseNoSep = HexString.fromHexString(dpidStrNoSep.toUpperCase(), null);
+ TestCase.assertTrue(Arrays.equals(validBytes, testBytes));
+ TestCase.assertTrue(Arrays.equals(validBytes, testBytesNoSep));
+ TestCase.assertTrue(Arrays.equals(validBytes, testBytesUCase));
+ TestCase.assertTrue(Arrays.equals(validBytes, testBytesUCaseNoSep));
+ }
+
+ @Test
public void testToLongError() {
String dpidStr = "09:08:07:06:05:04:03:02:01";
try {