简体   繁体   English

将十六进制字符串转换为 swift 上的数据

[英]convert hex string to Data on swift

I am a beginner developer, so I hope I can explain my problem correctly.我是初学者开发人员,所以我希望我能正确解释我的问题。

I get some data from a Bluetooth device, and then I use this code to encode the data and send them to an endpoint我从蓝牙设备获取一些数据,然后使用此代码对数据进行编码并将它们发送到端点

let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .deferredToData
let encodedData = try encoder.encode(data)
let finalArray = encodedData.compactMap { $0 }

and then...接着...

try JSONEncoder().encode(finalArray)

The final structure that send to server is not something that we expected.发送到服务器的最终结构不是我们所期望的。

so I used this extension to convert the data to hex string所以我使用这个扩展将数据转换为十六进制字符串

extension Data {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
        return map { String(format: format, $0) }.joined()
    }
}

The outcome is exactly looks that I expected, now I need to send the data to the endpoint, but I can't send the array of string to the sever, my question is how I can send the data as data with this new hex string format?结果完全符合我的预期,现在我需要将数据发送到端点,但我无法将字符串数组发送到服务器,我的问题是如何使用这个新的十六进制字符串将数据作为data发送格式?

thank you so much太感谢了

You can avoid converting your data to string and back to data manually encoding your bytes.您可以避免将数据转换为字符串并返回手动编码字节的数据。 Try like this:试试这样:

extension RangeReplaceableCollection where Element == UInt8 {
    var hexaEncoded: Self {
        reduce(.init()) {
            let a = $1 / 16
            let b = $1 % 16
            return $0 + [a + (a < 10 ? 48 : 87),
                         b + (b < 10 ? 48 : 87)]
        }
    }
}

extension Sequence where Element == UInt8 {
    var string: String? { String(bytes: self, encoding: .utf8) }
}

let data = Data([0,127,255]) // "007fff"
let hexaEncodedData = data.hexaEncoded // 6 bytes [48, 48, 55, 102, 102, 102]
let hexaEncodedString = hexaEncodedData.string  // "007fff"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM