Search code examples
iosobjective-cunicode

Get NSString Number Representation in Objective-C


I've been working on an encryption algorithm and now I'd like to encrypt an entire string instead of just numbers. How to I get the number Representation of each character in Objective-C? I already have an Array containing all the single characters of the given string, I just need to find a way to get a number out of it. I'm not sure if iOS uses unicode, but if Id just need to get the unicode value and convert it to a number right? But how do I do that?


Solution

  • Encryption algorithm usually operate on a sequence of bytes, so you should choose a string encoding to convert the NSString (which uses Unicode internally) to a byte sequence. For example:

    NSString *string = @"Hello World😄";
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@", data); //  <48656c6c 6f20576f 726c64f0 9f9884>
    const uint8_t *bytes = [data bytes]; // Pointer to UTF-8 bytes
    NSUInteger length = [data length];   // Number of UTF-8 bytes   
    

    Now you can encrypt bytes[0], ..., bytes[length-1] (which are all in the range 0 .. 255).