如何使用带Swift的位字段来存储超过1位的值

如何使用带Swift的位字段来存储超过1位的值,swift,struct,bit-fields,Swift,Struct,Bit Fields,在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 {

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;
}
所以我可以访问字节半字节的特定部分。 显然,这只是一个例子。可以创建适合基本类型的任何大小的位字段

尽管我付出了很多努力,做了很多研究,但我还是不知道如何在Swift中做到这一点。我可以使用bitwise来获得相同的结果,但这不是那么可读和优雅

有什么想法吗?

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)
扩展单元UInt8{
变量低字节:UInt8{
得到{
返回self&0x0F
}
设置(新值){
self=(self&0xF0)|(newValue&0x0F)
}
}
var highNibble:UInt8{
得到{
返回(self&0xF0)>>4
}
设置(新值){

self=(self&0x0F)|((newValue&0x0F)我正在写一个Chip-8虚拟机,在这种情况下,我必须使用位运算来访问整数的不同部分,就像你说的。谢谢你的帮助。Martin,Swift 2.1现在支持bitfields@dcunited001:如果我没记错的话,从C导入的结构中支持位字段,但不能在Swift中直接定义它们。位字段是b使用二进制操作一次访问一位存储器的asic结构。在硬件接口、通信或只是实现简单但非常有用的状态机方面非常关键。不管怎样,谁设计了这种语言…-/。也许他们会在Swift 5或Swift 6中实现更多的基础知识