get string length and format it first from integer to hexadecimal and then write literally the same value in a closed byte array

  1. Implement method to get 2-byte array representing length of the string
    Note: check max length of the input string and throw IllegalArgumentException
static byte[] getLengthHex(String message) {
    int len = null == message ? 0: message.length();
    if (len > 0xFFFF) {
        throw new IllegalArgumentException("Input string is too long, its length = " + len);
    }
    return new byte[] {(byte)(len >> 8 & 0xFF), (byte)(len & 0xFF)};
}
  1. Print the byte array using formatting:
String[] tests = {
    "1".repeat(147),
    "2".repeat(510),
    "3".repeat(10_001)
};

for (String t : tests) {
    byte[] len = getLengthHex(t);
    System.out.printf("%5d -> 0x%02X 0x%02X%n", t.length(), len[0], len[1]);
}

Output:

  147 -> 0x00 0x93
  510 -> 0x01 0xFE
10001 -> 0x27 0x11

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top