hex/binary string conversion in Swift

后端 未结 3 1565
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 23:38

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 ava

3条回答
  •  青春惊慌失措
    2020-11-28 00:26

    Not really familiar with Python and the checks it performs when convert the numbers, but you can expand the function below:

    func convert(_ str: String, fromRadix r1: Int, toRadix r2: Int) -> String? {
        if let num = Int(str, radix: r1) {
            return String(num, radix: r2)
        } else {
            return nil
        }
    }
    
    convert("11111111", fromRadix: 2, toRadix: 16)
    convert("ff", fromRadix: 16, toRadix: 2)
    

提交回复
热议问题