在C中:
typedef unsigned char u8;
typedef unsigned short u16;
typedef union {
struct { u8 l,h; } b;
u16 w;
} Register;
在Swift中(使用带有关联值的枚举):
enum Register {
case b(UInt8, UInt8)
case w(UInt16)
var l: UInt8 {
switch(self) {
case .b(let l, _): return l
case .w(let w): return UInt8(w)
}
}
var h: UInt8 {
switch(self) {
case .b(_, let h): return h
case .w(let w): return UInt8(w >> 8)
}
}
var w: UInt16 {
switch(self) {
case .b(let l, let h): return UInt16(l | (h << 8))
case .w(let w): return w
}
}
}
这有效:
let regA = Register.b(255, 0)
print(regA.l)
print(regA.h)
let regB = Register.w(UInt16(256))
print(regB.w)
但这不会导致运行时异常:
print(regA.w)
print(regB.l)
print(regB.h)
我无法找出问题,因为在枚举定义中跟踪该问题似乎非常不可能。
我看到两个问题。
对于问题1,您正在创建一个UInt8
from UInt16
,如果您不限制该值,它将溢出。您可以使用UInt8(truncatingBitPattern: w)
或UInt8(w & 0xff)
。
对于问题2,l
并h
在声明中UInt16(l | (h << 8))
有UInt8
值,所以你四溢UInt8
,你需要转换到UInt16
之前移位和或-ING。
您的代码现在可以进行以下2种修改:
enum Register {
case b(UInt8, UInt8)
case w(UInt16)
var l: UInt8 {
switch(self) {
case .b(let l, _): return l
case .w(let w): return UInt8(w & 0xff) // issue 1
}
}
var h: UInt8 {
switch(self) {
case .b(_, let h): return h
case .w(let w): return UInt8(w >> 8)
}
}
var w: UInt16 {
switch(self) {
case .b(let l, let h): return UInt16(l) | UInt16(h) << 8 // issue 2
case .w(let w): return w
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句