为了说明稍后用于较大数据类型(如 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/