Get Unicode point of NSString and place it in another NSString

What's the easiest way to get a Unicode value from NSString

? For example,

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


Now I want to set the value hex

to Unicode value str

(i.e. 0041) ... How should I do this?


source to share

2 answers

The type is unichar

defined as a 16-bit unicode value (for example, as indirectly documented in the% C specifier description ), and you can get unichar

from a given position in NSString

with, characterAtIndex:

or use getCharacters:range:

if you want to quickly populate the unichars C array from NSString

, and then query them one by one others.


is also valid string encoding as well as multiple choices defined for endian in case you want to be absolutely future proof. You will end up with a C array from those using a much longer one getBytes:maxLength:usedLength:encoding:options:range:remainingRange:


EDIT: so for example

NSString *str = @"A";

NSLog(@"16-bit unicode values are:");
for(int index = 0; index < [str length]; index++)
    NSLog(@"%04x", [str characterAtIndex:index]);




you can use

NSData * u = [str dataUsingEncoding:NSUnicodeStringEncoding];
NSString *hex = [u description];


You can replace NSUnicodeStringEncoding with NSUTF8StringEncoding, NSUTF16StringEncoding (same as NSUnicodeStringEncoding) or NSUTF32StringEncoding, or many other values.

See here  for more



All Articles