user198725878
user198725878

Reputation: 6386

iOS Convert Hex value

How to convert hexadecimal value into emoji icons , I have a string like below

NSString *myVal = @"1F61E";

how can i convert this text to display it as emoji charrcaters?

I have found that value from this link Please let me know, i am really stuck-up with this issue

Updated

NSString *utf8String1 = @"1F61E";
NSString *a = [self convert:utf8String1];
NSLog(@"%@ &&&&&&&&&&&&&&&&&&&&&",a);


-(NSString*)convert:(NSString*)decoded{

    unichar unicodeValue = (unichar) strtol([decoded UTF8String], NULL, 16);
    char buffer[2];
    int len = 1;

    if (unicodeValue > 127) {
        buffer[0] = (unicodeValue >> 8) & (1 << 8) - 1;
        buffer[1] = unicodeValue & (1 << 8) - 1; 
        len = 2;
    } else {
        buffer[0] = unicodeValue;
    }

    return [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];



}

Upvotes: 6

Views: 3055

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727037

The code point that you are trying to encode does not fit in 16 bits. Therefore you need to use UTF-32 encoding:

NSScanner *scan = [[NSScanner alloc] initWithString:@"1F61E"];
unsigned int val;
[scan scanHexInt:&val];
char cc[4];
cc[3] = (val >> 0) & 0xFF;
cc[2] = (val >> 8) & 0xFF;
cc[1] = (val >> 16) & 0xFF;
cc[0] = (val >> 24) & 0xFF;
NSString *s = [[NSString alloc]
    initWithBytes:cc
           length:4
         encoding:NSUTF32StringEncoding];
NSLog(@"[%@]", s);

Upvotes: 4

Richard J. Ross III
Richard J. Ross III

Reputation: 55583

Your first step is to convert it to it's numerical value:

unichar unicodeValue = (unichar) strtol([input UTF8String], NULL, 16);

Then, following from the rules of this post:

char buffer[2];
int len = 1;

if (unicodeValue > 127) {
    buffer[0] = (unicodeValue >> 8) & (1 << 8) - 1;
    buffer[1] = unicodeValue & (1 << 8) - 1; 
    len = 2;
} else {
    buffer[0] = unicodeValue;
}

return [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];

You now have your UTF-8 Formatted string!

Upvotes: 0

Related Questions