UTF-8 到代码点
我需要实现这样的方法: int toCodePoint(byte[] buf, int startIndex); 它应该将字节数组中的 UTF-8 字符解码为代码点。不应创建额外的对象(这就是我不使用 JDK String 类进行解码的原因)。 有没有现有的java类可以做到这一点? 谢谢。
I need to implement a method like this:
int toCodePoint(byte [] buf, int startIndex);
It should decode a UTF-8 char in byte array to code point. No extra objects should be created(that's the reason why I don't use JDK String class to do decode).
Are there any existing java classes to do this?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 java.nio.charset.CharsetDecoder< /a> 来做到这一点。您将需要一个
ByteBuffer
和一个CharBuffer
。将数据放入ByteBuffer
中,然后使用CharsetDecoder.decode(ByteBuffer in, CharBuffer out, boolean endOfInput)
读入CharBuffer
。然后,您可以使用Character.codePointAt(char[] a, int index)
获取代码点。使用此方法很重要,因为如果文本包含 BMP 之外的字符,它们将被转换为两个字符,因此仅读取一个字符是不够的。使用这种方法,你只需要创建两个缓冲区一次,之后除非发生一些错误,否则不会创建新的对象。
You can use java.nio.charset.CharsetDecoder to do that. You'll need a
ByteBuffer
and aCharBuffer
. Put the data intoByteBuffer
, then useCharsetDecoder.decode(ByteBuffer in, CharBuffer out, boolean endOfInput)
to read into theCharBuffer
. Then you can get the code point usingCharacter.codePointAt(char[] a, int index)
. It is important to use this method because if your text has characters outside the BMP, they will be translated into two chars, so it's not sufficient to read only one char.With this method you only need to create two buffers once, after that no new objects will be created unless some error occurs.
我知道的所有现有 Java 类都不适合此任务,因为您有限制(“不应创建额外的对象”)。否则,您可以使用 CharsetDecoder (如马尔科姆提到)。或者甚至走到黑暗面并使用 sun.io.ByteToCharUTF8如果您确实需要纯静态方法。但这不是推荐的方式。
All existing Java classes i know are not fits for this task, because you have restriction ("No extra objects should be created"). Otherwise you could use CharsetDecoder (as mentioned by Malcolm). Or even come to dark side and use sun.io.ByteToCharUTF8 if you really need pure static method. But it is not recommended way.