Skip to content

Consider using java.util.HexFormat #10

@rntrp

Description

@rntrp

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions