0

I need a code, to convert @"043b" to @"л"

Here is what I tried

// get a hex string (@"0x043b")
NSString *hexString = [@"0x" stringByAppendingString:@"043b"];

// scan an unsined int from it (1083 as expected)
NSScanner* pScanner = [NSScanner scannerWithString:hexString];
unsigned int iValue;
[pScanner scanHexInt: &iValue];

// get a unichar from it (';')
NSNumber *number = [NSNumber numberWithUnsignedInt:iValue];
unichar character = [number unsignedCharValue];

// get a string (@";")
NSString *result = [NSString stringWithFormat:@"%C", character];

but I get @";" instead of @"л"

I also tried

// get a char (';')
char character = [number charValue];

// get a string (@";")
NSString * result = [NSString stringWithFormat:@"%c", character];

Please, help!

Tim
  • 1,877
  • 19
  • 27
  • http://stackoverflow.com/questions/16812034/convert-hex-code-to-unicode-in-objective-c – urnotsam May 28 '15 at 18:46
  • Once you have the int use this post to finish your code: http://stackoverflow.com/questions/1775859/how-to-convert-a-unichar-value-to-an-nsstring-in-objective-c – Juan Catalan May 28 '15 at 18:55

2 Answers2

0

Here you go:

unsigned long hexBytes = 0x3b04;
NSString *theString = [[NSString alloc] initWithBytes:&hexBytes length:sizeof(hexBytes) encoding:NSUnicodeStringEncoding];
NSLog(theString, @"");

Important point: you have to reverse your bytes so it's 0x3b04 instead of 0x043b.

cbiggin
  • 1,942
  • 1
  • 17
  • 18
  • You may take a look at the solution I found. I does not require bytes reversing – Tim Jul 21 '15 at 11:26
0

This worked for me

int value = 0;
sscanf([@"043b" cStringUsingEncoding:NSUTF8StringEncoding], "%x", &value);

NSString *result = [NSString stringWithFormat:@"%C", value];

But the compiler is warning me on the last line, so the answer is not that clean

Format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'

Tested both on the 32- and 64-bit processors

Tim
  • 1,877
  • 19
  • 27