Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Unicode point of NSString and put that into another NSString

What's the easiest way to get the Unicode value from an NSString? For example,

NSString *str = "A";
NSString *hex;

Now, I want to set the value of hex to the Unicode value of str (i.e. 0041)... How would I go about doing that?

like image 673
citruspi Avatar asked Jan 17 '23 03:01

citruspi


1 Answers

The unichar type is defined to be a 16-bit unicode value (eg, as indirectly documented in the description of the %C specifier), and you can get a unichar from a given position in an NSString using characterAtIndex:, or use getCharacters:range: if you want to fill a C array of unichars from the NSString more quickly than by querying them one by one.

NSUTF32StringEncoding is also a valid string encoding, as are a couple of endian-specific variants, in case you want to be absolutely future proof. You'd get a C array of those using the much more longwinded getBytes:maxLength:usedLength:encoding:options:range:remainingRange:.

EDIT: so, e.g.

NSString *str = @"A";

NSLog(@"16-bit unicode values are:");
for(int index = 0; index < [str length]; index++)
    NSLog(@"%04x", [str characterAtIndex:index]);
like image 156
Tommy Avatar answered Jan 30 '23 22:01

Tommy