将表示HEX值的NSString转换为十六进制(@" 0d"到0x0d)

时间:2017-08-04 10:07:37

标签: ios objective-c c hex

我想转换ObjectiveC NSString,其中包含例如string" 0d"到十六进制值0x0d。最简单的方法是什么?

示例:

NSString *str = @"50";
unsigned char mac[1];
mac[0] = 0x50; //<- how to set mac[0] to 0x50 from "str" string?

1 个答案:

答案 0 :(得分: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;
}