Swift 中的 Unsigned Int 到负 Int [英] Unsigned Int to negative Int in Swift

查看:55
本文介绍了Swift 中的 Unsigned Int 到负 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 Pebble 加速度计数据,需要将负整数的无符号表示转换为正常数字(例如,注意前两个).

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]

使用Objective C 我已经通过简单的[number intValue] 设法做到了这一点.但是,使用 Swift 我找不到这样做的方法.我试过 Int(number),但得到相同的值.

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.

推荐答案

如果您收到错误的类型,您可以随时执行 unsafeBitcast:

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

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

例如将 UInt32 转换为 Int32

vacawama 展示了一个更好的解决方案,没有令人讨厌的unsafe:

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

这篇关于Swift 中的 Unsigned Int 到负 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆