Given a hexadecimal string in Swift, convert to hex value

后端 未结 4 714
难免孤独
难免孤独 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 19:04

    Swift 3 version, modified from @Martin R's answer. This variant also accepts incoming string with odd length.

    let string = "D7C17A4F"
    
    let chars = Array(string.characters)
    let numbers = stride(from: 0, to: chars.count, by: 2).map() {
        strtoul(String(chars[$0 ..< min($0 + 2, chars.count)]), nil, 16)
    }
    

提交回复
热议问题