Reputation: 406
I need to convert a string to unicode (hex) char, I am to to do unicode to string using the below code
[NSString stringWithFormat:@"%C",0x2665];
but I am not able to exactly reverse of this.
What will be the code snippet for this
Upvotes: 1
Views: 3270
Reputation: 118
custom unicode to emoji
#define EmojiCodeToSymbol(c) ((((0x808080F0 | (c & 0x3F000) >> 4) | (c & 0xFC0) << 10) | (c & 0x1C0000) << 18) | (c & 0x3F) << 24)
/// convert hexadecimal to unicode
/// NSString *v = omgEmojiConvertCode(@"0x1F580");
/// v is 🖀 (cannot be displayed),
static inline NSString *omgEmojiConvertCode(NSString * code) {
char *charCode = (char *)code.UTF8String;
long intCode = strtol(charCode, NULL, 16);
NSString *s = [NSString stringWithFormat:@"%ld",intCode];
int symbol = EmojiCodeToSymbol([s intValue]);
NSString *string = [[NSString alloc] initWithBytes:&symbol length:sizeof(symbol) encoding:NSUTF8StringEncoding];
return string;
}
Upvotes: 1
Reputation: 629
Thanks to objective C. It has encoding methods which helps the Unicode to string and string to Unicode. Here is the sample.
NSString *str = @"♥";
NSData *dataenc = [str dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *encodevalue = [[NSString alloc]initWithData:dataenc encoding:NSUTF8StringEncoding];
NSData *data = [encodevalue dataUsingEncoding:NSUTF8StringEncoding];
NSString *decodevalue = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];
NSLog(@"%@",decodevalue);
Upvotes: 4
Reputation: 138261
It depends on what your definition of a character is. Given your example, I'd assume that [string characterAtIndex:0]
is what you're looking for (get the first unichar
value contained in the string, which would be 0x2665 for the string created in your first example).
However, you're getting an UTF-16 code point out of it, which may or may not be a complete logical character, and which may or may not be a complete character as printed. For instance, this will fail to represent some emojis, and will definitely fail to represent any emoji with a special skin color, or country flags. (Importantly, it can also fail to represent the characters of some languages.)
Upvotes: 1