数据丢失对我来说不是问题。
var temp1:Int32 = 45058
var temp2:Int32 = -20345
var temp3:Int32 = -40345
var temp4:Int16 = Int16(temp1)//overflow
var temp5:Int16 = Int16(temp2)//return wrog value
var temp6:Int16 = Int16(temp3)//overflow
也试过这个,但它也返回了错误的值,这不是我想要的。
temp4 = Int16(temp1 & 0x0000ffff)//overflow
在我的 C 代码中,没有任何问题,因为 c 编译器自己执行此操作。
这其实很简单,你只需要明确说出你想做什么:
var temp4: Int16 = Int16(truncatingIfNeeded: temp1) // -20478
var temp5: Int16 = Int16(truncatingIfNeeded: temp2) // -20345
var temp6: Int16 = Int16(truncatingIfNeeded: temp3) // 25191
(该方法在 Swift 3 中称为 truncatingBitPattern:
)
truncatingIfNeeded
会将较低的 16 位重新解释为 Int16
。
请注意,在这种情况下,& 0xffff
不起作用。默认初始值设定项正在尝试转换数值,而不是位值,不幸的是45058
,否则0xB002
将& 0xffff
保持不变,并且不适合Int16
。不过,这将适用于无符号整数。