最近做一个数据缓存的地方用到了NSData Hex String 互转,查阅了相关资料,链接如下
相关链接
https://stackoverflow.com/questions/7317860/converting-hex-nsstring-to-nsdata
https://stackoverflow.com/questions/1305225/best-way-to-serialize-an-nsdata-into-a-hexadeximal-string
代码如下
hex string to NSData
- (NSData *)convertDataBaseStoredStringToData:(NSString *)command
{
if (![command isKindOfClass:[NSString class]]) {
return [NSData data];
}
command = [command stringByReplacingOccurrencesOfString:@">" withString:@""];
command = [command stringByReplacingOccurrencesOfString:@"<" withString:@""];
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];
}
return commandToSend;
}
NSData to hex String
- (NSMutableString *)dataToHexString:(NSData *)valueData insertSql:(NSMutableString *)insertSql {
if (@available(iOS 13, *)) {
if ([valueData isKindOfClass:[NSData class]]) {
NSMutableString *valueString = [NSMutableString string];
const char *bytes = valueData.bytes;
NSInteger count = valueData.length;
for (int i = 0; i < count; i++) {
[valueString appendFormat:@"%02x", bytes[i]&0x000000FF];
}
[insertSql appendFormat:@"'%@',", [valueString stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
} else {
[insertSql appendFormat:@"'%@',", [[NSString stringWithFormat:@"%@", valueData] stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
}
} else {
[insertSql appendFormat:@"'%@',", [[NSString stringWithFormat:@"%@", valueData] stringByReplacingOccurrencesOfString:@"'" withString:@"''"]];
}
return insertSql;
}
网友评论