Carmelo Cascone

Added possibility to decode HEX strings without separator

Change-Id: I6e11ad2a3dc4e39b148a740d5f19d80705f78b48
(cherry picked from commit 6eaa33ab)
......@@ -109,7 +109,25 @@ public final class HexString {
* @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++) {
......
......@@ -21,6 +21,9 @@ import com.esotericsoftware.minlog.Log;
import junit.framework.TestCase;
import java.nio.ByteBuffer;
import java.util.Arrays;
import static org.junit.Assert.fail;
/**
......@@ -55,6 +58,22 @@ public class HexStringTest {
}
@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 {
......