LoginSignup
0
1

More than 3 years have passed since last update.

Swiftでbitでフラグ管理する

Last updated at Posted at 2021-04-12

動機

bitでフラグ管理してsetみたいなものを作りたい。

必要なbitオペレーション

  • フラグが立っているかどうかの確認
(bit & 1<<i) != 0
  • iビット目を立てる
bit | (1<<i)
  • iビット目を消す
bit & ~(1<<i)

作ったもの

struct BitSet {

    var bit: Int = 0

    func contain(i: Int) -> Bool {
        return (bit & 1<<i) > 0
    }

    mutating func insert(i: Int, raise: Bool) {
        self.bit = raise ? bit | (1<<i) : bit & ~(1<<i)
    }
}

参考

0
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1