Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned Int to negative Int in Swift

I'm working with the Pebble accelerometer data and need to convert the unsigned representations of negative ints 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 do so by the simple [number intValue]. However, using Swift I can't find a way to do so. I've tried Int(number), but I get the same value.

like image 985
Marti Serra Vivancos Avatar asked Jan 08 '23 19:01

Marti Serra Vivancos


2 Answers

You can always do an unsafeBitcast if you received the wrong type:

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

This for example converts an UInt32 to an Int32

EDIT: vacawama showed a better solution without the nasty unsafe:

Int32(bitPattern: 4294967009)

Thanks a lot! Use this one instead, it's safe (obviously) and probably faster

like image 111
Kametrixom Avatar answered Jan 15 '23 22:01

Kametrixom


You can use bitPattern in the constructor to convert unsigned to signed:

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 a 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"
like image 40
vacawama Avatar answered Jan 15 '23 22:01

vacawama