[英]How can I mask or convert Int32 to Int16 in swift
Data loss is no problem for me. 数据丢失对我来说没问题。
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
Also tried this, but it is also returning wrong value, it is not what I want. 也尝试了这个,但它也返回错误的值,它不是我想要的。
temp4 = Int16(temp1 & 0x0000ffff)//overflow
In my C code, there is no any issue because c compiler does this by self. 在我的C代码中,没有任何问题,因为c编译器通过self执行此操作。
This is actually very simple, you just have to say explicitly what you want to do: 这实际上非常简单,你只需明确说明你想做什么:
var temp4: Int16 = Int16(truncatingIfNeeded: temp1) // -20478
var temp5: Int16 = Int16(truncatingIfNeeded: temp2) // -20345
var temp6: Int16 = Int16(truncatingIfNeeded: temp3) // 25191
(the method is called truncatingBitPattern:
in Swift 3) (该方法在Swift 3中称为
truncatingBitPattern:
:)
truncatingIfNeeded
will reinterpret the lower 16 bits as Int16
. truncatingIfNeeded
将低16位重新解释为Int16
。
Note that & 0xffff
won't work in this case. 请注意,
& 0xffff
在这种情况下不起作用。 The default initializer is trying to convert the numeric value , not the bit value and unfortunately 45058
, or 0xB002
will be unchanged through & 0xffff
and it won't fit Int16
. 默认的初始化程序试图转换数值 ,而不是位值,不幸的是
45058
或0xB002
将通过& 0xffff
保持不变,它不适合Int16
。 That would work for unsigned integers though. 这虽然适用于无符号整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.