4

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.

Marti Serra Vivancos
  • 1,195
  • 5
  • 17
  • 33

3 Answers3

5

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

Community
  • 1
  • 1
Kametrixom
  • 14,673
  • 7
  • 45
  • 62
  • 2
    Can also be done with `Int32(bitPattern: 4294967009)` which doesn't have that nasty `unsafe` word in it. :-) – vacawama Aug 07 '15 at 16:04
4

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"
vacawama
  • 150,663
  • 30
  • 266
  • 294
0

Are you just trying to convert an unsigned representation of a negative number into it's signed representation? If so, this should work:

let negativeValue = Int((incomingValue - 0xffffffff) % 0xffffffff)
GoatInTheMachine
  • 3,583
  • 3
  • 25
  • 35