Java 17 introduced java.util.HexFormat, which provides a concise (and most likely hardware‑optimized) API for encoding and decoding hexadecimal data. Altcha has two methods which utilize custom hex conversion logic:
|
static byte[] hexToBytes(String hex) { |
|
if (hex.length() % 2 != 0) throw new IllegalArgumentException("Hex string must have even length: " + hex); |
|
var bytes = new byte[hex.length() / 2]; |
|
for (var i = 0; i < bytes.length; i++) { |
|
bytes[i] = (byte) Integer.parseInt(hex, i * 2, i * 2 + 2, 16); |
|
} |
|
return bytes; |
|
} |
|
public static String bytesToHex(byte[] bytes) { |
|
var sb = new StringBuilder(2 * bytes.length); |
|
for (var b : bytes) { |
|
var hex = Integer.toHexString(0xff & b); |
|
if (hex.length() == 1) sb.append('0'); |
|
sb.append(hex); |
|
} |
|
return sb.toString(); |
|
} |
These method bodies can be replaced with HexFormat.of() one-liners:
return HexFormat.of().parseHex(hex); (maybe retain the custom exception logic for API compatibility)
return HexFormat.of().formatHex(bytes)
Please consider using HexFormat.of() for better readability and performance.
Java 17 introduced
java.util.HexFormat, which provides a concise (and most likely hardware‑optimized) API for encoding and decoding hexadecimal data. Altcha has two methods which utilize custom hex conversion logic:altcha-lib-java/src/main/java/org/altcha/altcha/v2/Altcha.java
Lines 852 to 859 in 5ba5379
altcha-lib-java/src/main/java/org/altcha/altcha/v2/Altcha.java
Lines 861 to 869 in 5ba5379
These method bodies can be replaced with
HexFormat.of()one-liners:return HexFormat.of().parseHex(hex);(maybe retain the custom exception logic for API compatibility)return HexFormat.of().formatHex(bytes)Please consider using
HexFormat.of()for better readability and performance.