Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String of hex to an Int [duplicate]

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?

like image 277
Syzygy Avatar asked Oct 16 '25 02:10

Syzygy


1 Answers

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))")
}
like image 66
Code Different Avatar answered Oct 18 '25 18:10

Code Different



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!