Given a hexadecimal string in Swift, convert to hex value

后端 未结 4 717
难免孤独
难免孤独 2021-01-06 18:30

Suppose I am given a string like this:

D7C17A4F

How do I convert each individual character to a hex value?

So D

4条回答
  •  一整个雨季
    2021-01-06 18:43

    here is the more generic, "pure swift" approach (no Foundation required :-))

    extension UnsignedInteger {
        var hex: String {
            var str = String(self, radix: 16, uppercase: true)
            while str.characters.count < 2 * MemoryLayout.size {
                str.insert("0", at: str.startIndex)
            }
            return str
        }
    }
    
    extension Array where Element: UnsignedInteger {
        var hex: String {
            var str = ""
            self.forEach { (u) in
                str.append(u.hex)
            }
            return str
        }
    }
    
    let str = [UInt8(1),22,63,41].hex  // "01163F29"
    let str2 = [UInt(1),22,63,41].hex  // "00000000000000010000000000000016000000000000003F0000000000000029"
    
    extension String {
        func toUnsignedInteger()->[T]? {
            var ret = [T]()
            let nibles = MemoryLayout.size * 2
            for i in stride(from: 0, to: characters.count, by: nibles) {
                let start = self.index(startIndex, offsetBy: i)
                guard let end = self.index(start, offsetBy: nibles, limitedBy: endIndex),
                    let ui = UIntMax(self[start..

    It is very easily to do the same for SignedInteger as well, but better approach will be to map results to signed type

    let u8 = u1?.map { Int8(bitPattern: $0) }                    // [-14, 52, 95]
    

提交回复
热议问题