Bytes to Data
let bytes: UInt8 = [0x01, 0x10]
let data = Data.init(bytes: bytes)
Data to Bytes
let bytes = [UInt8](data)
Hex String to Data
extension String {
func hexadecimal() -> Data? {
var data = Data(capacity: characters.count / 2)
let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
regex.enumerateMatches(in: self, range: NSMakeRange(0, utf16.count)) { match, flags, stop in
let byteString = (self as NSString).substring(with: match!.range)
var num = UInt8(byteString, radix: 16)!
data.append(#, count: 1)
}
guard data.count > 0 else { return nil }
return data
}
}
Data to Hex String
extension Data {
func hexadecimal() -> String {
return map { String(format: "%02x", $0) }
.joined(separator: "")
}
}
hexString转Data的用法:
let hexString = "68656c6c 6f2c2077 6f726c64"
let data:Data = (String.hexadecimal(hexString)())!