简体   繁体   English

Java-Objective C字符UTF-8问题

[英]Java - Objective C char UTF-8 issue

I have a little issue with Java UTF-8 converting.I have this Objective C code : 我对Java UTF-8转换有一点问题。我有这个Objective C代码:

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. 其中md5Hash是NSString ,我需要找到一种方法来在Java中声明相同的char p ,但没有找到如何将char设置为UTF-8。

Any ideas or suggestions? 有什么想法或建议吗?

I don't know about Objective C, but in Java chars are UTF-16 and Strings internal char buffer are that way. 我不了解Objective C,但是在Java中,chars是UTF-16,而Strings 内部 char缓冲区就是这种方式。 You can convert from and to UTF-8 if you need: 如果需要,可以从和转换为UTF-8:

// 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... 注意:如果您需要流解决方案,则还可以使用InputStreamReader和OutputStreamWriter进行此非常相同的转换,但这是另一回事了...

In Java, a String contains unicode characters, and you don't care about its encoding until you transform it to a byte array. 在Java中,字符串包含Unicode字符,在将其转换为字节数组之前,您无需关心其编码。 Look at String.getBytes(String charsetName) . 查看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. String类具有一个构造函数,您可以在其中传递一个字节数组及其编码作为参数。

IO classes also have a way to write/read strings to/from a binary stream using a specific encoding. IO类还具有一种使用特定编码向二进制流写入字符串或从二进制流读取字符串的方法。 Look at the constructors of OutputStreamWriter and InputStreamReader . 查看OutputStreamWriterInputStreamReader的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM