最近在完成一個(gè)需求時(shí),遇到了NSData
類型轉(zhuǎn)換為十六進(jìn)制的字符串這個(gè)需求的函數(shù),在stackoverflow
中翻找的時(shí)候甜橱,給出的答案基本上是如下的:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
// If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.
NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];
// (Note that if the input is not properly UTF-8-encoded, you will get nil.)
Swift的寫(xiě)法
let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.
// If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.
// safe way, provided data is \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))
但是在實(shí)際的測(cè)試中车份,并不能完成將NSData轉(zhuǎn)換為NSData中存儲(chǔ)的十六進(jìn)制字符串的功能歉摧,所以在最終找到答案之后缤谎,決定記錄下來(lái)抒倚,以便下次使用可以快速查找。
- (NSData *)convertHexStrToData:(NSString *)str {
if (!str || [str length] == 0) {
return nil;
}
NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
NSRange range;
if ([str length] % 2 == 0) {
range = NSMakeRange(0, 2);
} else {
range = NSMakeRange(0, 1);
}
for (NSInteger i = range.location; i < [str length]; i += 2) {
unsigned int anInt;
NSString *hexCharStr = [str substringWithRange:range];
NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
[hexData appendData:entity];
range.location += range.length;
range.length = 2;
}
NSLog(@"hexdata: %@", hexData);
return hexData;
}
傳入?yún)?shù)字符串@"400"
時(shí)坷澡,打印出來(lái)的是 hexdata: <0400>
托呕。十六進(jìn)制的400就是10進(jìn)制的1024。
- (NSString *)convertDataToHexStr:(NSData *)data {
if (!data || [data length] == 0) {
return @"";
}
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
unsigned char *dataBytes = (unsigned char*)bytes;
for (NSInteger i = 0; i < byteRange.length; i++) {
NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
if ([hexStr length] == 2) {
[string appendString:hexStr];
} else {
[string appendFormat:@"0%@", hexStr];
}
}
}];
return string;
}
將上一個(gè)??的NSData作為參數(shù)傳入時(shí)频敛,返回的字符串為400
项郊。轉(zhuǎn)換完成。