简体   繁体   中英

Java - Objective C char UTF-8 issue

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?

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...

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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