gpt4 book ai didi

swift - 如何快速屏蔽或将 Int32 转换为 Int16

转载 作者:可可西里 更新时间:2023-11-01 00:00:02 27 4
gpt4 key购买 nike

数据丢失对我来说不是问题。

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。不过,这适用于无符号整数。

关于swift - 如何快速屏蔽或将 Int32 转换为 Int16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46907910/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com