dreadbot
dreadbot

Reputation: 962

How to convert unsigned char to NSString in iOS

Can anyone tell me how to convert an unsigned char to an NSString?

Here's the code I am using, but for some reason if I try to do anything with the NSString, like set a UITextView text, it gives me an error. The NSLog works correctly though. Thanks in advance.

- (void)onTagReceived:(unsigned char *)tag
{

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *myTag = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x\n",tag[0],tag[1],tag[2],tag[3],tag[4]];

NSLog(@"currentTag: %@",myTag);

[displayTxt setText:myTag];

[pool release];

}

Upvotes: 13

Views: 19392

Answers (2)

Manoj
Manoj

Reputation: 1003

@jtbandes: you are correct. The other way you can do this:

NSString *str = [NSString stringWithCString:tag length:strlen(tag)];

Upvotes: 3

jtbandes
jtbandes

Reputation: 118681

If tag is a C string (null-terminated, that is), then you can use [NSString stringWithUTF8String:(char *)tag]. If you want the hex values, then your code using %02x is fine.

Upvotes: 22

Related Questions