相关文章推荐
深沉的领结  ·  [转]windows BLE编程 net ...·  1 周前    · 
纯真的围巾  ·  aggregate - mongodb ...·  11 月前    · 
着急的板栗  ·  java - Execution ...·  1 年前    · 
俊逸的石榴  ·  metatrader5 - ...·  1 年前    · 

1.十六进制String(字符串)转Data

1.1 方法一(推荐):

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<UInt8>)
   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", $0) }
            .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 data:Data = Data.init(bytes: self)
        return data.hexadecimal()

3.2 bytes[UInt8],Data,NSData转十六进制字符串,mac地址“AA:BB:CC:DD:EE:FF”

extension NSData {
    func macStr()->String {
        var bytes:[UInt8] = [UInt8](self as Data)
        bytes.removeFirst()
        bytes.removeFirst()
        var macStr = bytes.toHexStr()
        return macStr.uppercased()
extension Data {
    /// Create hexadecimal string representation of `Data` object.
    /// - returns: `String` representation of this `Data` object.
    func macStr() -> String {
        return map { String(format: "%02x", $0) }
            .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 data:Data = Data.init(bytes: self)
        return data.macStr()

3.2 可以用CryptoSwift框架中的数据转换方法

数据加密和转换的框架:
CryptoSwift - github

4.Data转十六进制String

extension Data {
    /// Create hexadecimal string representation of `Data` object.
    /// - returns: `String` representation of this `Data` object.
    func hexadecimal() -> String {
        return map { String(format: "%02x", $0) }
            .joined(separator: "")

5.Data,NSData,bytes[UInt8]互转

playground
在这里插入图片描述

bytes: [UInt8]

let data:Data = Data.init(bytes: bytes);         
let nsdata:NSData = NSData.init(bytes: bytes, length: bytes.count);

data: Data

let bytes: [UInt8] = [UInt8](data)  
let nsdata: NSData = NSData(data: data)

nsdata: NSData

let bytes: [UInt8] = [UInt8](nsdata as Data)
let data: Data = nsdata as Data

参考博客:

(iOS, Swift)十六进制转Data,十六进制转整形,Data转String
swift 16进制String和Data相互转换
Swift中,把NSData转换为Byte数组的三种方法

for (let i = 0; i < b.length; i++) { let hex = (b[i]).toString(16); if (hex.length === 1) { hexs = '0' + hex; hexs += hex.toUpperCase();
本文实例讲述了javascript实现的字符串十六进制表示字符串互转换方法。分享给大家供大家参考。具体如下: 之所以写这个,是因为发现SQL注入和XSS中经常利用十六进制表示的字符串,比如 SELECT CONCAT(0x68656c6c6f); 得到的是hello <!DOCTYPE html> <title>Hex-Char Bi-Converter</title> </head> <div class=mainContainer> <label for=from id=fromLabel>String</la
- (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)b; 初始化对象。 不进行复制字节数组操作,直接设置字节指针为bytes,长度为length。 - (instancetype)i... let nowDate = Date() let timeZone = TimeZone.init(identifier: "UTC") let formatter = DateFormatter()
1 String 类型 NSData 类型        dataUsingEncoding函数: 将字符串类型(String)的数据换成数据类型(NSData) 的数据。 String类中有自带的函数方法: public dataUsingEncoding(encoding: NSStringEncoding, allowLossyC
日期字符串。这个虽然简单,但是我相信很多朋友初次遇到肯定束手无策。脑子里蹦出四个字:这怎么?直接上代码: //获取系统当前时间 NSDate *currentDate = [NSDate date]; //用于格式化NSDate对象 NSDateFormatter *dateFormatter = [[NSDat... + (NSString *)hexStringFromString:(NSString *)string NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding]; Byte *bytes = (Byte *)[myD bytes]; //下面是Byte 换为16进制。 NSMutableString* resultStr = [[NSMutableString alloc]in #pragma mark - 十六进制换工具 // 16进制NSData - (NSData *)convertHexStrToData:(NSString *)str if (!str || [str length] == 0) { return nil; NSMutableData *hexData = [[NSMutableDa... ```cpp QString hexString = "1A2B3C"; QByteArray hexData = QByteArray::fromHex(hexString.toUtf8()); qDebug() << hexData.toHex(); 这里将字符串"1A2B3C"换为QByteArray类型的hexData,再使用toHex方法输出16进制数值。