將HEX NSString轉換為NSData我正在嘗試將十六進制轉換NSString為NSData(我正在使用下面附加的代碼)。以下是輸出:<00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000>這看起來與我完全無關。關于哪里出錯的任何想法/建議?NSString *strData = @"72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553";NSLog(@"string Data length is %d",[strData length]);NSMutableData *commandToSend= [[NSMutableData alloc] init];unsigned char whole_byte;char byte_chars[2];int i;for (i=0; i < [strData length]/2; i++) { byte_chars[0] = [strData characterAtIndex:i*2]; byte_chars[1] = [strData characterAtIndex:i*2+1]; whole_byte = strtol(byte_chars, NULL, [strData length]); [commandToSend appendBytes:&whole_byte length:1]; }NSLog(@"%@", commandToSend);
3 回答

素胚勾勒不出你
TA貢獻1827條經(jīng)驗 獲得超9個贊
NSString *command = @"72ff63cea198b3edba8f7e0c23acc345050187a0cde5a9872cbab091ab73e553";command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];NSMutableData *commandToSend= [[NSMutableData alloc] init];unsigned char whole_byte;char byte_chars[3] = {'\0','\0','\0'};int i;for (i=0; i < [command length]/2; i++) { byte_chars[0] = [command characterAtIndex:i*2]; byte_chars[1] = [command characterAtIndex:i*2+1]; whole_byte = strtol(byte_chars, NULL, 16); [commandToSend appendBytes:&whole_byte length:1]; }NSLog(@"%@", commandToSend);

神不在的星期二
TA貢獻1963條經(jīng)驗 獲得超6個贊
這可能更有用,Apple已經(jīng)共享了NSData類別。
代碼是:
@implementation NSData (HexString)// Not efficent+(id)dataWithHexString:(NSString *)hex{ char buf[3]; buf[2] = '\0'; NSAssert(0 == [hex length] % 2, @"Hex strings should have an even number of digits (%@)", hex); unsigned char *bytes = malloc([hex length]/2); unsigned char *bp = bytes; for (CFIndex i = 0; i < [hex length]; i += 2) { buf[0] = [hex characterAtIndex:i]; buf[1] = [hex characterAtIndex:i+1]; char *b2 = NULL; *bp++ = strtol(buf, &b2, 16); NSAssert(b2 == buf + 2, @"String should be all hex digits: %@ (bad digit around %d)", hex, i); } return [NSData dataWithBytesNoCopy:bytes length:[hex length]/2 freeWhenDone:YES];}@end
- 3 回答
- 0 關注
- 815 瀏覽
添加回答
舉報
0/150
提交
取消