获取字符串长度并对其进行格式化,首先从整数到十六进制,然后将其按字面意思写入字节数组中的相同值
Get string length and format it, first from integer to hexadecimal, and then, write it literally the same value inside a byte array
我想在 Java 中创建一个具有以下原型的函数:
public byte[] serializeToByteArray(String message)
它接收一个字符串作为参数。
里面的函数,要计算消息的长度,然后转成16进制。
转为十六进制后,得return两个字节,长度为十六进制。
示例 1:
- 字符串长度:147
- Return 值:字节[] = {0x00, 0x93}
示例 2:
- 字符串长度:510
- Return 值:字节[] = {0x01, 0xFE}
示例 3:
- 字符串长度:10.001
- Return 值:字节[] = {0x27, 0x11}
- 实现方法以获取表示字符串长度的 2 字节数组
注意:检查输入字符串的最大长度并抛出 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)};
}
- 使用格式打印字节数组:
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]);
}
输出:
147 -> 0x00 0x93
510 -> 0x01 0xFE
10001 -> 0x27 0x11
我想在 Java 中创建一个具有以下原型的函数:
public byte[] serializeToByteArray(String message)
它接收一个字符串作为参数。
里面的函数,要计算消息的长度,然后转成16进制。 转为十六进制后,得return两个字节,长度为十六进制。
示例 1:
- 字符串长度:147
- Return 值:字节[] = {0x00, 0x93}
示例 2:
- 字符串长度:510
- Return 值:字节[] = {0x01, 0xFE}
示例 3:
- 字符串长度:10.001
- Return 值:字节[] = {0x27, 0x11}
- 实现方法以获取表示字符串长度的 2 字节数组
注意:检查输入字符串的最大长度并抛出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)};
}
- 使用格式打印字节数组:
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]);
}
输出:
147 -> 0x00 0x93
510 -> 0x01 0xFE
10001 -> 0x27 0x11