如何在 Swift 中使用位字段来存储超过 1 位的值 [英] How to use bit field with Swift to store values with more than 1 bit

查看:29
本文介绍了如何在 Swift 中使用位字段来存储超过 1 位的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C 中,我可以这样做:

In C I can do something like this:

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;
}

所以我可以访问 byte_nibbles 的特定部分.显然这只是一个例子.可以创建适合基本类型的任意大小的位域.

So I can access specific parts of the byte_nibbles. Obviously this is just one example. It is possible to create bit fields of any size that fits in the basic types.

尽管我付出了努力并进行了大量研究,但我无法弄清楚如何在 Swift 中做到这一点.我可以使用按位得到相同的结果,但这不是那么可读和优雅.

Despite my efforts and a lot of research I could not figure out how to do this in Swift. I can use bitwise to have the same result, but this is not as readable and elegant.

有什么想法吗?

推荐答案

Swift 只是不支持位域,所以你只能

Swift simply does not support bit fields, so you can only

  • 改用下一个更大的整数类型(在您的情况下Int8)并接受变量需要更多内存,或者
  • 使用位操作来访问整数的不同部分.
  • use the next larger integer type instead (in your case Int8) and accept that the variables need more memory, or
  • use bit operations to access the different parts of the integer.

对于第二种情况,您可以定义自定义计算属性以减轻访问.举个例子:

For the second case you could define custom computed properties to ease the access. As an example:

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)

这篇关于如何在 Swift 中使用位字段来存储超过 1 位的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆