Android-Droid
Android-Droid

Reputation: 14585

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?

Upvotes: 0

Views: 532

Answers (2)

JB Nizet
JB Nizet

Reputation: 692071

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.

Upvotes: 1

helios
helios

Reputation: 13841

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

Upvotes: 2

Related Questions