gpt4 book ai didi

java - 在不实际编码的情况下计算 Java String 的 UTF-8 长度

转载 作者:IT老高 更新时间:2023-10-28 20:45:25 26 4
gpt4 key购买 nike

有谁知道标准 Java 库(任何版本)是否提供了一种计算字符串二进制编码长度(在这种情况下特别是 UTF-8)长度而不实际生成编码输出的方法?换句话说,我正在寻找一个有效的等价物:

"some really long string".getBytes("UTF-8").length

我需要为可能很长的序列化消息计算长度前缀。

最佳答案

这是一个基于 UTF-8 specification 的实现。 :

public class Utf8LenCounter {
public static int length(CharSequence sequence) {
int count = 0;
for (int i = 0, len = sequence.length(); i < len; i++) {
char ch = sequence.charAt(i);
if (ch <= 0x7F) {
count++;
} else if (ch <= 0x7FF) {
count += 2;
} else if (Character.isHighSurrogate(ch)) {
count += 4;
++i;
} else {
count += 3;
}
}
return count;
}
}

此实现不能容忍格式错误的字符串。

这是一个用于验证的 JUnit 4 测试:

public class LenCounterTest {
@Test public void testUtf8Len() {
Charset utf8 = Charset.forName("UTF-8");
AllCodepointsIterator iterator = new AllCodepointsIterator();
while (iterator.hasNext()) {
String test = new String(Character.toChars(iterator.next()));
Assert.assertEquals(test.getBytes(utf8).length,
Utf8LenCounter.length(test));
}
}

private static class AllCodepointsIterator {
private static final int MAX = 0x10FFFF; //see http://unicode.org/glossary/
private static final int SURROGATE_FIRST = 0xD800;
private static final int SURROGATE_LAST = 0xDFFF;
private int codepoint = 0;
public boolean hasNext() { return codepoint < MAX; }
public int next() {
int ret = codepoint;
codepoint = next(codepoint);
return ret;
}
private int next(int codepoint) {
while (codepoint++ < MAX) {
if (codepoint == SURROGATE_FIRST) { codepoint = SURROGATE_LAST + 1; }
if (!Character.isDefined(codepoint)) { continue; }
return codepoint;
}
return MAX;
}
}
}

请原谅紧凑的格式。

关于java - 在不实际编码的情况下计算 Java String 的 UTF-8 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8511490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com