swift - 从 2 个 UInt8 创建一个 UInt16

标签 swift

为了说明稍后用于较大数据类型(如 UInt128)的概念, 和 UInt256 ,我正在尝试执行以下功能:

我的函数需要 2 UInt8 s,将第一个(理论上更重要的位)向左移动 8,然后添加 int2 , (理论上是低位)

func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
   let x: UInt16 = (int1 << 8) + int2
   return x
}

我需要做些什么来避免错误:(int1 << 8) + int2不等于指定类型 UInt16

最佳答案

您必须明确地将较小的类型转换为较大的类型:

func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
    let x: UInt16 = (UInt16(int1) << 8) + UInt16(int2)
    return x
}

这也使得显式类型注释变得不必要:

func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
    let x = (UInt16(int1) << 8) + UInt16(int2)
    return x
}

它可以缩短为:

func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
    return UInt16(int1) << 8 + UInt16(int2)
}

必须在移动/添加之前转换为更大的类型, 否则可能会溢出。

关于swift - 从 2 个 UInt8 创建一个 UInt16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47658570/

相关文章:

swift - 使用转换(_ :to:) or convert(_:from:) to convert a node's position to another's

ios - UICollectionView 单元格的 Material 波纹效果

swift - UIButton 在 swift 中作为 UIButton?

bash - 带有默认值和killall bash命令的NSTask

ios - 在 Swift 的 TableView 中填充数据时出现问题

ios - 使用 Xcode 制作可滚动的项目菜单列表

ios - 如何完全删除 NSTimer SchedulerWithTimeInterval

swift - 如何使用 SwiftUI 和 CoreData (@FetchRequest) 对动态列表排序进行动画处理

variables - 通过尽可能多地定义常量而不是变量在 Swift 中有什么好处吗?

asynchronous - swift iOS8 : perform segue after TouchID authentication