如何在Swift中将String转换为UInt32

时间:2016-01-04 01:14:42

标签: string swift uint32

let temp: String = "0xffeeffff"

如何将上面的String转换为UInt32,因为我需要将它存储在只接受UInt32的位图中

2 个答案:

答案 0 :(得分:2)

从字符串中删除“0x”以将其转换为UInt32:

let temp   = "0xffeeffff"
let result = UInt32(String(temp.characters.dropFirst(2)), radix: 16)

答案 1 :(得分:1)

希望这对你有所帮助......

extension String {
func toUInt() -> UInt? {
    if contains(self, "-") {
        return nil
    }
    return self.withCString { cptr -> UInt? in
        var endPtr : UnsafeMutablePointer<Int8> = nil
        errno = 0
        let result = strtoul(cptr, &endPtr, 10)
        if errno != 0 || endPtr.memory != 0 {
            return nil
        } else {
            return result
        }
    }
}
}