Ces*_*nes 5 struct bit-fields swift
在C我可以做这样的事情:
struct byte_nibbles {
unsigned char b1: 4;
unsigned char b2: 4;
unsigned char b3: 4;
unsigned char b4: 4;
unsigned char b5: 4;
unsigned char b6: 4;
unsigned char b7: 4;
unsigned char b8: 4;
};
union {
unsigned long var;
struct byte_nibbles b;
}
u;
int main(void)
{
u.b.b1=0x01; u.b.b2=0x02; u.b.b3=0x03; u.b.b4=0x04;
u.b.b5=0x05; u.b.b6=0x06; u.b.b7=0x07; u.b.b8=0x08;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我可以访问 byte_nibbles 的特定部分。显然这只是一个例子。可以创建适合基本类型的任何大小的位域。
尽管我付出了努力并进行了大量研究,但我无法弄清楚如何在Swift 中做到这一点。我可以使用按位获得相同的结果,但这不是那么可读和优雅。
任何的想法?
Swift 根本不支持位域,所以你只能
Int8)并接受变量需要更多内存,或者对于第二种情况,您可以定义自定义计算属性以简化访问。举个例子:
extension UInt8 {
var lowNibble : UInt8 {
get {
return self & 0x0F
}
set(newValue) {
self = (self & 0xF0) | (newValue & 0x0F)
}
}
var highNibble : UInt8 {
get {
return (self & 0xF0) >> 4
}
set(newValue) {
self = (self & 0x0F) | ((newValue & 0x0F) << 4)
}
}
}
var byte : UInt8 = 0
byte.lowNibble = 0x01
byte.highNibble = 0x02
print(byte.lowNibble)
print(byte.highNibble)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1598 次 |
| 最近记录: |