How to use bit field with Swift to store values with more than 1 bit

岁酱吖の 提交于 2019-12-01 18:57:40

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

  • 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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!