将十六进制 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);
I'm trying to convert a Hex NSString
to NSData
(I'm using the below attached code). The following is the output:
<00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000>
which looks totally irrelevant to me. Any idea/ suggestions on where its going wrong?
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是另一种方法,它还处理前导
<
、尾随>
和嵌入空格,例如Code:
这是基于 @Nikunj R. Jadav 的答案
Here is another method that also handles leading
<
, trailing>
and embedded spaces such asCode:
This is based on the answer by @Nikunj R. Jadav
这可能更有用,Apple 共享了一个 NSData 类别。
NSData+HexString.m
代码是:
This might be more useful, Apple has shared a NSData category.
NSData+HexString.m
The code is:
我看到发布的几个解决方案只能转换偶数长度的字符串。
所以这是我的解决方案,如果字符串是奇数长度,如“DBA”变成这样的数据,它也能够返回正确的数据“\x0D\xBA”
I see several solution have been post only able to convert string with even length.
So here is my solution which also able return correct data if the string is odd length like this "DBA" became data like this this "\x0D\xBA"