gpt4 book ai didi

swift - fatal error : Not enough bits to represent the passed value (Int16) in Swift

转载 作者:行者123 更新时间:2023-12-05 00:43:45 28 4
gpt4 key购买 nike

我正在将一个库从 Java (Android) 转换为 -> Swift (iPhone)

Java 代码,工作正常:

   long a = 48590108397870l;
short b = ((short)(a & 65535));//b == -28370

Swift 代码:

    let a : Int64  = 48590108397870
let b: Int16 = Int16(a & 65535)//Fatal error: Not enough bits to represent the passed value

最佳答案

a & 65535 是介于 0 和 216-1 之间的值,适合 UInt16,但不适合 Int16。与许多其他语言相反,Swift 不会隐式截断值。

整数有 init(truncatingIfNeeded:)做你想做的事的初始化器:

When the bit width of T (the type of source) is equal to or greater than this type’s bit width, the result is the truncated least-significant bits of source.

例子:

let a : Int64 = 48590108397870
let b = Int16(truncatingIfNeeded: a)
print(b) // -28370

另一种选择是先创建一个无符号整数,然后将其转换为具有相同位模式的有符号整数:

let a : Int64 = 48590108397870
let b = Int16(bitPattern: UInt16(a & 0xFFFF))
print(b) // -28370

关于swift - fatal error : Not enough bits to represent the passed value (Int16) in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68650125/

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