Unsigned Int to negative Int in Swift

I am working with Pebble accelerometer data and have to convert unsigned representations of negative int to normal numbers (note the first two for example).

[X: 4294967241, Z: 4294967202, Y: 22] [X: 4294967278, Z: 4294967270, Y: 46] [X: 4294967274, Z: 4294967278, Y: 26] [X: 4294967221, Z: 85, Y: 4294967280] [X: 4294967247, Z: 117, Y: 4294967266]

Using Objective C I've managed to keep it simple [number intValue]

. However, using Swift, I cannot find a way to do this. I tried Int(number)

but get the same value.

+3


source to share


3 answers


You can always do unsafeBitcast

if you get the wrong type:

unsafeBitCast(UInt32(4294967009), Int32.self)  // -287

      

This, for example, converts a UInt32

toInt32



EDIT: vacawama showed the best solution without the nasty one unsafe

:

Int32(bitPattern: 4294967009)

      

Thank you so much! Use this instead, it's safe (obviously) and probably faster

+3


source


You can use bitPattern

in constructor to convert unsigned to signature:

let x = Int32(bitPattern: 4294967009)
print(x)  // prints "-287"

      

or if your value is already stored in a variable:



let x: UInt32 = 4294967241
let y = Int32(bitPattern: x)
print(y)  // prints "-55"

      

If your value is stored as 64-bit UInt

, you need to use truncatingBitPattern

when converting to Int32

:

let x: UInt = 4294967241
let y = Int(Int32(truncatingBitPattern: x))
print(y)  // prints "-55"

      

+2


source


Are you just trying to convert the unsigned representation of a negative number to this signed representation? If so, this should work:

let negativeValue = Int((incomingValue - 0xffffffff) % 0xffffffff)

      

0


source







All Articles