Java - Objective C char UTF-8 问题

发布于 2024-12-02 13:39:27 字数 281 浏览 1 评论 0原文

我在 Java UTF-8 转换方面遇到了一个小问题。我有这个 Objective C 代码:

const char *p = [[NSString stringWithFormat:@"0x%@",md5Hash] UTF8String];

其中 md5Hash 是 NSString 并且我需要找到一种方法来声明相同的 char p在Java中但没有找到如何将char设置为UTF-8。

有什么想法或建议吗?

I have a little issue with Java UTF-8 converting.I have this Objective C code :

const char *p = [[NSString stringWithFormat:@"0x%@",md5Hash] UTF8String];

where md5Hash is NSString and I need to find a way to declare the same char p in Java but didn't find how to set char to UTF-8.

Any ideas or suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

友欢 2024-12-09 13:39:27

我不知道 Objective C,但在 Java 中,字符是 UTF-16,字符串内部字符缓冲区也是这样。如果需要,您可以在 UTF-8 之间进行转换:

// creates a String from the bytes understanding them as UTF-8 chars
byte[] data = ...
new String(data, "UTF-8"); 

或者

// get the bytes that would represent that string in UTF-8
String myString = "Hello";
myString.getBytes("UTF-8"); 

希望它有帮助...

注意:如果您需要流解决方案,您还可以使用 InputStreamReader 和 OutputStreamWriter 进行相同的转换,但这是另一个问题故事...

I don't know about Objective C, but in Java chars are UTF-16 and Strings internal char buffer are that way. You can convert from and to UTF-8 if you need:

// creates a String from the bytes understanding them as UTF-8 chars
byte[] data = ...
new String(data, "UTF-8"); 

or

// get the bytes that would represent that string in UTF-8
String myString = "Hello";
myString.getBytes("UTF-8"); 

Hope it helps...

Note: if you need an streaming solution you can also use InputStreamReader and OutputStreamWriter for this very same transformation but that's another story...

唐婉 2024-12-09 13:39:27

在 Java 中,字符串包含 unicode 字符,在将其转换为字节数组之前,您不必关心它的编码。看看 <代码>String.getBytes(String charsetName)。如果您有一个字节数组并希望将其设为字符串,则还需要指定编码。 String 类有一个构造函数,您可以在其中传递字节数组及其编码作为参数。

IO 类还可以使用特定编码向二进制流写入字符串或从二进制流读取字符串。查看OutputStreamWriterInputStreamReader 的构造函数。

In Java, a String contains unicode characters, and you don't care about its encoding until you transform it to a byte array. Look at String.getBytes(String charsetName). If you have a byte array and want to make it a String, you also need to specify the encoding. The String class has a constrcutor where you pass a byte array and its encoding as argument.

IO classes also have a way to write/read strings to/from a binary stream using a specific encoding. Look at the constructors of OutputStreamWriter and InputStreamReader.

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