0

I want to convert ObjectiveC NSString, that contains for example string "0d" to hex value 0x0d. What's the easiest way to achieve that?

Example:

NSString *str = @"50";
unsigned char mac[1];
mac[0] = 0x50; //<- how to set mac[0] to 0x50 from "str" string?
Donald Duck
  • 8,409
  • 22
  • 75
  • 99
OldFox
  • 425
  • 2
  • 7
  • 19

1 Answers1

0
- (NSData *)dataFromHexString {
    const char *chars = [self UTF8String];
    int i = 0, len = self.length;

    NSMutableData *data = [NSMutableData dataWithCapacity:len/2];
    char byteChars[3] = {chars[0],chars[1],'\0'};
    unsigned long wholeByte = strtoul(byteChars, NULL, 16);
    [data appendBytes:&wholeByte length:1];

    return data;
}
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84