UTF-8 到代码点

发布于 2025-01-05 07:06:05 字数 153 浏览 0 评论 0原文

我需要实现这样的方法: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

前事休说 2025-01-12 07:06:05

You can use java.nio.charset.CharsetDecoder to do that. You'll need a ByteBuffer and a CharBuffer. Put the data into ByteBuffer, then use CharsetDecoder.decode(ByteBuffer in, CharBuffer out, boolean endOfInput) to read into the CharBuffer. Then you can get the code point using Character.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.

心头的小情儿 2025-01-12 07:06:05

我知道的所有现有 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文