將 NSData 轉換為 HEX 字串
NSData
可以表示為十六進位制字串,類似於它在 description
方法中輸出的字串。
迅速
extension NSData {
func hexString() -> String {
return UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(bytes), count: length)
.reduce("") { $0 + String(format: "%02x", $1) }
}
}
Objective-C
@implementation NSData (HexRepresentation)
- (NSString *)hexString {
const unsigned char *bytes = (const unsigned char *)self.bytes;
NSMutableString *hex = [NSMutableString new];
for (NSInteger i = 0; i < self.length; i++) {
[hex appendFormat:@"%02x", bytes[i]];
}
return [hex copy];
}
@end