- Implement method to get 2-byte array representing length of the string
Note: check max length of the input string and throwIllegalArgumentException
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)};
}
- 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.