extension String {
/// Create `Data` from hexadecimal string representation
///
/// This takes a hexadecimal representation and creates a `Data` object. Note, if the string has any spaces or non-hex characters (e.g. starts with '<' and with a '>'), those are ignored and only hex characters are processed.
///
/// - returns: Data represented by this hexadecimal string.
func hexadecimal() -> Data? {
var data = Data(capacity: self.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(&num, count: 1)
}
guard data.count > 0 else { return nil }
return data
}
}
1.2 方法二:
//将十六进制字符串转化为 Data
func data(from hexStr: String) -> Data {
var hexStr1 = ""
if hexStr.count % 2 != 0 {
hexStr1 = "0" + hexStr
}else {
hexStr1 = hexStr
}
let bytes = self.bytes(from: hexStr1)
return Data(bytes: bytes)
}
2.十六进制字符串转bytes[UInt8]
// 将16进制字符串转化为 [UInt8]
// 使用的时候直接初始化出 Data
// Data(bytes: Array)
func bytes(from hexStr: String) -> [UInt8] {
// print("hexStr:\(hexStr)")
assert(hexStr.count % 2 == 0, "输入字符串格式不对,8位代表一个字符")
var bytes = [UInt8]()
var sum = 0
// 整形的 utf8 编码范围
let intRange = 48...57
// 小写 a~f 的 utf8 的编码范围
let lowercaseRange = 97...102
// 大写 A~F 的 utf8 的编码范围
let uppercasedRange = 65...70
for (index, c) in hexStr.utf8CString.enumerated() {
var intC = Int(c.byteSwapped)
if intC == 0 {
break
} else if intRange.contains(intC) {
intC -= 48
} else if lowercaseRange.contains(intC) {
intC -= 87
} else if uppercasedRange.contains(intC) {
intC -= 55
} else {
assertionFailure("输入字符串格式不对,每个字符都需要在0~9,a~f,A~F内")
}
sum = sum * 16 + intC
// 每两个十六进制字母代表8位,即一个字节
if index % 2 != 0 {
bytes.append(UInt8(sum))
sum = 0
}
}
// print(bytes)
print(bytes.count)
return bytes
}
3.bytes[UInt8]转十六进制字符串Hex
3.1 自己的代码和示例
示例
let bytes:[UInt8] = [0xff,0xaa,0xbb]
print(bytes)
print(bytes.toHexStr())
代码打印结果:
[255, 170, 187]
ff-aa-bb
extension Data {
//MARK: Data转十六进制字符串
/// Create hexadecimal string representation of `Data` object.
///
/// - returns: `String` representation of this `Data` object.
func hexadecimal() -> String {
return map { String(format: "%02x", )} .
joined(:separator"-" )}
}
extension
Array where Element == UInt8 //MARK: bytes[UInt8]转十六进制字符串 {
/// Create hexadecimal string representation of `Data` object.
///
/// - returns: `String` representation of this `Data` object.
func
toHexStr ()String -> let {
: dataData= Data .init(:bytesself )return
. datahexadecimal()}
}
extension
3.2 可以用CryptoSwift框架中的数据转换方法
数据加密和转换的框架:
CryptoSwift - github
Data /// Create hexadecimal string representation of `Data` object. {
///
/// - returns: `String` representation of this `Data` object.
func
hexadecimal ()String -> return {
String map { (:format"%02x" ,) }. joined
(:""separator) }}
let
=
5.Data,NSData,bytes[UInt8]互转
playground
bytes: [UInt8]
( data:Data ) Data.init;bytes: byteslet=
( nsdata:NSData ) NSData.init;bytes: bytes, length: bytes.countlet[
data: Data
] bytes: =UInt8[ ] (UInt8)letdata=
( nsdata: NSData ) NSDataletdata: data[
nsdata: NSData
] bytes: =UInt8[ ] (UInt8)letnsdata as Data=
data: Data nsdata as Data
参考博客:
(iOS, Swift)十六进制转Data,十六进制转整形,Data转String
swift 16进制String和Data相互转换
Swift中,把NSData转换为Byte数组的三种方法
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)