将十六进制的String转换为Int

时间:2017-01-13 22:24:20

标签: swift numbers int hex

我在Swift工作,我把这个字符串作为输入:"0x13123ac"
我希望Int作为输出:0x13123ac

我该怎么做?

1 个答案:

答案 0 :(得分:6)

你的问题毫无意义。计算机以二进制存储数字,而非十六进制也许您想要的是将十六进制字符串转换为整数并将其转换回十六进制以用于显示目的:

let input = "0x13123ac"

// Int(_, radix: ) can't deal with the '0x' prefix. NSScanner can handle hex
// with or without the '0x' prefix
let scanner = Scanner(string: input)
var value: UInt64 = 0

if scanner.scanHexInt64(&value) {
    print("Decimal: \(value)")
    print("Hex: 0x\(String(value, radix: 16))")
}
相关问题