通过将NSString解释为hex数字来创建NSData

Edit1: rob mayoff’answer很精彩。这是我自己的:

-(NSData *)change:(NSString *)hexString { int j=0; Byte bytes[[hexString length]]; for(int i=0;i= '0' && hex_char1 = 'A' && hex_char1 = '0' && hex_char2 = 'A' && hex_char1 <='F') int_ch2 = hex_char2-55; else int_ch2 = hex_char2-87; int_ch = int_ch1+int_ch2; bytes[j] = int_ch; j++; } NSData *newData = [[NSData alloc] initWithBytes:bytes length:[hexString length]/2]; return newData; } 

——-编辑单独—————————————– ——-

我有一个hex数字的NSString,如下所示:

 NSString *aString =@“” 

我想将它更改为NSData,如下所示:

 NSData *aData =  

有人能告诉我怎么做吗?

我想你所说的是你有一个NSString ,你想要将字符串中的字符解释为hex数字,并创建一个NSData其内容是由这些hex数字表示的字节。 我已经编辑了你的问题。

有很多方法可以做到这一点。 这是一个完全没有优化的,不能优雅地处理错误。 但我确实在你的例子上测试了它。

 NSData *dataByIntepretingHexString(NSString *hexString) { char const *chars = hexString.UTF8String; NSUInteger charCount = strlen(chars); if (charCount % 2 != 0) { return nil; } NSUInteger byteCount = charCount / 2; uint8_t *bytes = malloc(byteCount); for (int i = 0; i < byteCount; ++i) { unsigned int value; sscanf(chars + i * 2, "%2x", &value); bytes[i] = value; } return [NSData dataWithBytesNoCopy:bytes length:byteCount freeWhenDone:YES]; } 
 -(NSMutableData*)hexDataFromString:(NSString*)string{ NSMutableData *hexData= [[NSMutableData alloc] init]; unsigned char whole_byte; char byte_chars[3] = {'\0','\0','\0'}; int i; for (i=0; i < [string length]/2; i++) { byte_chars[0] = [string characterAtIndex:i*2]; byte_chars[1] = [string characterAtIndex:i*2+1]; whole_byte = strtol(byte_chars, NULL, 16); [hexData appendBytes:&whole_byte length:1]; } return hexData; } 

接受的答案,同时充分展示了这个想法。 由于sscanf可能会遇到性能问题。 另一个答案可能应该被赞成。 以下可能是帮助,但不检查格式错误的数据。

 +(uint8_t)hexCharacterValue:(unichar)hexChar{ if(hexChar > 0x60) return (hexChar - 0x57); if(hexChar > 0x40) return (hexChar - 0x37); return (hexChar - 0x30); } +(NSData*)dataWithOctetString:(NSString*)string{ NSUInteger byteCount = [string length]/2; uint8_t* bytes = (uint8_t*) malloc(byteCount*sizeof(uint8_t)); for(NSUInteger j = 0, i=0; j<[string length]; j+=2,i++) bytes[i] = ([[self class] hexValue:[string characterAtIndex:j]] << 4) | [[self class] hexValue:[string characterAtIndex:j+1]]; return [NSData dataWithBytesNoCopy:bytes length:byteCount freeWhenDone:YES]; }