Skip to content

Commit

Permalink
Faster byte array to hex string generator
Browse files Browse the repository at this point in the history
Signed-off-by: Shay Gordon <shay@blockchaintp.com>
  • Loading branch information
camembertelectrique committed Jun 22, 2020
1 parent 8e94d2b commit 9bdfdf0
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions utils/src/main/java/org/web3j/utils/Numeric.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
public final class Numeric {

private static final String HEX_PREFIX = "0x";
private static final char[] HEX_CHAR_MAP = "0123456789abcdef".toCharArray();

private Numeric() {}

Expand Down Expand Up @@ -227,15 +228,18 @@ public static byte[] hexStringToByteArray(String input) {
}

public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) {
StringBuilder stringBuilder = new StringBuilder();
if (withPrefix) {
stringBuilder.append("0x");
}
for (int i = offset; i < offset + length; i++) {
stringBuilder.append(String.format("%02x", input[i] & 0xFF));
}
final String output = new String(toHexCharArray(input, offset, length, withPrefix));
return withPrefix ? new StringBuilder(HEX_PREFIX).append(output).toString() : output;
}

return stringBuilder.toString();
public static char[] toHexCharArray(byte[] input, int offset, int length, boolean withPrefix) {
final char[] output = new char[length << 1];
for (int i = offset; i < length; i++) {
final int v = input[i] & 0xFF;
output[i * 2] = HEX_CHAR_MAP[v >>> 4];
output[i * 2 + 1] = HEX_CHAR_MAP[v & 0x0F];
}
return output;
}

public static String toHexString(byte[] input) {
Expand Down

0 comments on commit 9bdfdf0

Please sign in to comment.