How to convert an NSString to hex values

Posted by einsteinx2 on Stack Overflow See other posts from Stack Overflow or by einsteinx2
Published on 2010-06-16T20:02:06Z Indexed on 2010/06/16 20:32 UTC
Read the original article Hit count: 991

Filed under:
|

I'd like to convert a regular NSString into an NSString with the (what I assume are) ASCII hex values and back.

I need to produce the same output that the Java methods below do, but I can't seem to find a way to do it in Objective-C. I've found some examples in C and C++ but I've had a hard time working them into my code.

Here are the Java methods I'm trying to reproduce:

/**
* Encodes the given string by using the hexadecimal representation of its UTF-8 bytes.
*
* @param s The string to encode.
* @return The encoded string.
*/
public static String utf8HexEncode(String s) {
    if (s == null) {
        return null;
    }
    byte[] utf8;
    try {
        utf8 = s.getBytes(ENCODING_UTF8);
    } catch (UnsupportedEncodingException x) {
        throw new RuntimeException(x);
    }
    return String.valueOf(Hex.encodeHex(utf8));
}

/**
* Decodes the given string by using the hexadecimal representation of its UTF-8 bytes.
*
* @param s The string to decode.
* @return The decoded string.
* @throws Exception If an error occurs.
*/
public static String utf8HexDecode(String s) throws Exception {
if (s == null) {
    return null;
}
    return new String(Hex.decodeHex(s.toCharArray()), ENCODING_UTF8);
} 

© Stack Overflow or respective owner

Related posts about iphone

Related posts about objective-c