From 7aecce79438eddcb59ce327d8418c24910691b5a Mon Sep 17 00:00:00 2001 From: kai-morich Date: Sun, 30 Jul 2023 09:43:50 +0200 Subject: [PATCH] util/HexDump with space separated hex strings --- .../com/hoho/android/usbserial/util/HexDump.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/HexDump.java b/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/HexDump.java index 3de78fc..ac95c83 100644 --- a/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/HexDump.java +++ b/usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/HexDump.java @@ -20,7 +20,7 @@ import java.security.InvalidParameterException; /** * Clone of Android's /core/java/com/android/internal/util/HexDump class, for use in debugging. - * Cosmetic changes only. + * Changes: space separated hex strings */ public class HexDump { private final static char[] HEX_DIGITS = { @@ -82,10 +82,12 @@ public class HexDump { } public static String toHexString(byte[] array, int offset, int length) { - char[] buf = new char[length * 2]; + char[] buf = new char[length > 0 ? length * 3 - 1 : 0]; int bufIndex = 0; for (int i = offset; i < offset + length; i++) { + if (i > offset) + buf[bufIndex++] = ' '; byte b = array[i]; buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F]; buf[bufIndex++] = HEX_DIGITS[b & 0x0F]; @@ -139,12 +141,13 @@ public class HexDump { throw new InvalidParameterException("Invalid hex char '" + c + "'"); } + /** accepts any separator, e.g. space or newline */ public static byte[] hexStringToByteArray(String hexString) { int length = hexString.length(); - byte[] buffer = new byte[length / 2]; + byte[] buffer = new byte[(length + 1) / 3]; - for (int i = 0; i < length; i += 2) { - buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString.charAt(i + 1))); + for (int i = 0; i < length; i += 3) { + buffer[i / 3] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString.charAt(i + 1))); } return buffer;