Using string encoding other than NSStringEncoding

I ran into the problem the other day of having to encode a string using CP037 encoding, to communicate with the server. This turned out to be tricky than I had hoped because CP037 is not in the NSStringEncoding enum list of encoding directly supported by NSString.


I did managed to find support for CP037 in CFStringEncodingExt as kCFStringEncodingEBCDIC_CP037. I know that NSString and CFString toll-free bridged data types so all I had to do was encode my NSString using CFString encoding and I would have the value that I needed to send to the server.

       NSString *stringThatNeedsToBeEncoded = @"randomString";
       CFDataRef encodedStringAsCFData = CFStringCreateExternalRepresentation(CFAllocatorGetDefault(), (CFStringRef)stringThatNeedsToBeEncoded, kCFStringEncodingEBCDIC_CP037, 0);

        CFIndex bufferLength = CFDataGetLength(encodedStringAsCFData);
        UInt8 *buffer = malloc(bufferLength);
        CFDataGetBytes(encodedStringAsCFData, CFRangeMake(0, CFDataGetLength(encodedStringAsCFData)), buffer);

And inside buffer I had my byte array which I needed.