本文介绍了NSString(十六进制)转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Objective-C中有没有将十六进制字符串转换为字节的方法?例如 @1156FFCD3430AA22
到无符号字符数组{0x11,0x56,0xFF,...}
。 解决方案
$ b我可以想到的最快的NSString类别实现$ b
- (NSData *)dataFromHexString {
const char * chars = [self UTF8String];
int i = 0,len = self.length;
NSMutableData * data = [NSMutableData dataWithCapacity:len / 2];
char charChar [3] = {'\0','\0','\0'};
unsigned long wholeByte;
while(i< len){
byteChars [0] = chars [i ++];
byteChars [1] = chars [i ++];
wholeByte = strtoul(byteChars,NULL,16);
[data appendBytes:& wholeByte length:1];
}
返回数据;
}
它比wookay的解决方案快8倍。 NSScanner非常慢。
Is there any method in Objective-C that converts a hex string to bytes? For example @"1156FFCD3430AA22"
to an unsigned char array {0x11, 0x56, 0xFF, ...}
.
解决方案
Fastest NSString category implementation that I could think of (cocktail of some examples):
- (NSData *)dataFromHexString {
const char *chars = [self UTF8String];
int i = 0, len = self.length;
NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
char byteChars[3] = {'\0','\0','\0'};
unsigned long wholeByte;
while (i < len) {
byteChars[0] = chars[i++];
byteChars[1] = chars[i++];
wholeByte = strtoul(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
}
return data;
}
It is close to 8 times faster than wookay's solution. NSScanner is quite slow.
这篇关于NSString(十六进制)转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!