3

I'm working in Swift and I have this string as input: "0x13123ac"
And I want an Int as output: 0x13123ac

How can I do that?

jscs
  • 63,694
  • 13
  • 151
  • 195
Syzygy
  • 123
  • 2
  • 9

1 Answers1

11

Your question makes no sense. Computers store numbers in binary, not hex. Perhaps what you wanted was to convert a hex string to an integer and convert it back to hex for display purposes:

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))")
}
Code Different
  • 90,614
  • 16
  • 144
  • 163