十六进制/二进制字符串转换在Swift中 [英] hex/binary string conversion in Swift

查看:1030
本文介绍了十六进制/二进制字符串转换在Swift中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python有两个非常有用的库方法(binascii.a2b_hex(keyStr)和binascii.hexlify(keyBytes)),我一直在Swift中苦苦挣扎。 Swift中是否有任何可用的东西?如果不是,那么如何实现它?给定所有的界限和其他检查(如偶数长度键)。

/ code>从Swift 3没有内置的方法来打印它的内容为
a十六进制字符串,或从一个数据值创建一个十六进制字符串。



数据到十六进制字符串方法可以找到,例如在如何将数据转换为十六进制字符串在迅速或者如何打印变量类型数据使用swift?将字符串转换为数据swift 3.0 。以下是第一个链接的实现:

 扩展数据{
func hexEncodedString() - > String {
return map {String(format:%02hhx,$ 0)} .joined()
}
}

这是一个可能的反转十六进制字符串到数据
转换的实现(摘自 Code Review上的十六进制字符串到字节(NSData),翻译成Swift 3并改进)
作为failable inititializer:

 扩展数据{

init?(fromHexEncodedString string:String){

/ /将0 ... 9,a ... f,A ... F转换为它们的十进制值,
//返回所有其他输入字符的零值
func decodeNibble(u:UInt16) - > ; UINT8? {
switch(u){
case 0x30 ... 0x39:
return UInt8(u - 0x30)
case 0x41 ... 0x46:
return UInt8 u - 0x41 + 10)
case 0x61 ... 0x66:
return UInt8(u - 0x61 + 10)
default:
return nil
}
}

self.init(容量:string.utf16.count / 2)
var even = true
var byte:UInt8 = 0
for c in string .utf16 {
guard let val = decodeNibble(u:c)else {return nil}
if even {
byte = val<< 4
} else {
byte + = val
self.append(byte)
}
even =!even
}
guard even else {return nil}
}
}

示例:

  //数据的十六进制字符串:
如果let data = Data(fromHexEncodedString:0002468A13579BFF){
let idata = Data(data.map {255 - $ 0})

//数据到十六进制字符串:
print(idata.hexEncodedString())// fffdb975eca86400
} else {
print(无效的十六进制字符串)
}


Python has two very useful library method (binascii.a2b_hex(keyStr) and binascii.hexlify(keyBytes)) which I have been struggling with in Swift. Is there anything readily available in Swift. If not, how would one implement it? Given all the bounds and other checks (like even-length key) are done.

解决方案

Data from Swift 3 has no "built-in" method to print its contents as a hex string, or to create a Data value from a hex string.

"Data to hex string" methods can be found e.g. at How to convert Data to hex string in swift or How to print the content of a variable type Data using swift? or converting string to data in swift 3.0. Here is an implementation from the first link:

extension Data {
    func hexEncodedString() -> String {
        return map { String(format: "%02hhx", $0) }.joined()
    }
}

Here is a possible implementation of the reverse "hex string to Data" conversion (taken from Hex String to Bytes (NSData) on Code Review, translated to Swift 3 and improved) as a failable inititializer:

extension Data {

    init?(fromHexEncodedString string: String) {

        // Convert 0 ... 9, a ... f, A ...F to their decimal value,
        // return nil for all other input characters
        func decodeNibble(u: UInt16) -> UInt8? {
            switch(u) {
            case 0x30 ... 0x39:
                return UInt8(u - 0x30)
            case 0x41 ... 0x46:
                return UInt8(u - 0x41 + 10)
            case 0x61 ... 0x66:
                return UInt8(u - 0x61 + 10)
            default:
                return nil
            }
        }

        self.init(capacity: string.utf16.count/2)
        var even = true
        var byte: UInt8 = 0
        for c in string.utf16 {
            guard let val = decodeNibble(u: c) else { return nil }
            if even {
                byte = val << 4
            } else {
                byte += val
                self.append(byte)
            }
            even = !even
        }
        guard even else { return nil }
    }
}

Example:

// Hex string to Data:
if let data = Data(fromHexEncodedString: "0002468A13579BFF") {
    let idata = Data(data.map { 255 - $0 })

    // Data to hex string:
    print(idata.hexEncodedString()) // fffdb975eca86400
} else {
    print("invalid hex string")
}

这篇关于十六进制/二进制字符串转换在Swift中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆