Skip to content

Commit 8a449bd

Browse files
committed
Minor performance improvement en/decoding hex
1 parent 02c27b5 commit 8a449bd

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/main/java/at/favre/lib/bytes/BinaryToTextEncoding.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,12 @@ public String encode(byte[] byteArray, ByteOrder byteOrder) {
8787
StringBuilder sb = new StringBuilder(byteArray.length * 2);
8888

8989
int index;
90+
char first4Bit;
91+
char last4Bit;
9092
for (int i = 0; i < byteArray.length; i++) {
9193
index = (byteOrder == ByteOrder.BIG_ENDIAN) ? i : byteArray.length - i - 1;
92-
char first4Bit = Character.forDigit((byteArray[index] >> 4) & 0xF, 16);
93-
char last4Bit = Character.forDigit((byteArray[index] & 0xF), 16);
94+
first4Bit = Character.forDigit((byteArray[index] >> 4) & 0xF, 16);
95+
last4Bit = Character.forDigit((byteArray[index] & 0xF), 16);
9496
if (upperCase) {
9597
first4Bit = Character.toUpperCase(first4Bit);
9698
last4Bit = Character.toUpperCase(last4Bit);
@@ -115,9 +117,11 @@ public byte[] decode(CharSequence hexString) {
115117

116118
int len = hexString.length();
117119
byte[] data = new byte[(len - start) / 2];
120+
int first4Bits;
121+
int second4Bits;
118122
for (int i = start; i < len; i += 2) {
119-
int first4Bits = Character.digit(hexString.charAt(i), 16);
120-
int second4Bits = Character.digit(hexString.charAt(i + 1), 16);
123+
first4Bits = Character.digit(hexString.charAt(i), 16);
124+
second4Bits = Character.digit(hexString.charAt(i + 1), 16);
121125

122126
if (first4Bits == -1 || second4Bits == -1) {
123127
throw new IllegalArgumentException("'" + hexString.charAt(i) + hexString.charAt(i + 1) + "' at index " + i + " is not hex formatted");

0 commit comments

Comments
 (0)