Reputation: 2480
I've seen a lot of questions converting hex to int, but these are all of the unsigned-> unsigned variety. How could I convert signed hex to an Int?
eg.
somefunc('0xfffff830')
= -2000
Upvotes: 3
Views: 1873
Reputation: 539975
Your question implies that you are dealing with 32-bit signed integers
(otherwise 0xfffff830
could not be considered as negative),
so this would work:
let num = "0xfffff830"
let x = Int32(truncatingBitPattern: strtoul(num, nil, 16))
println(x) // -2000
strtoul()
converts the hex string to an unsigned integer UInt
, and
Int32(truncatingBitPattern:)
creates a (signed) 32-bit integer
from the lowest 32 bits of the given argument.
Updated for Swift 4:
let num = "0xfffff830"
let x = Int32(bitPattern: UInt32(num.dropFirst(2), radix: 16) ?? 0)
print(x) // -2000
Upvotes: 7
Reputation: 285200
An approach
var hex = UInt32(0xfffff830)
let signedHex : Int
if hex > UInt32.max / 2 {
signedHex = -Int(~hex + 1) // ~ is the Bitwise NOT Operator
} else {
signedHex = Int(hex)
}
Upvotes: 1
Reputation: 11555
You could use conversion to unsigned and then convert the unsigned to signed.
let num = "0xfffff830"
var result: UInt32 = 0
let converter = NSScanner(string: num)
converter.scanHexInt(&result)
print(unsafeBitCast(result, Int32.self)) // prints -2000
Upvotes: 2