Last active
August 9, 2024 09:52
-
-
Save T1T4N/b53bdd911a5d0433efae6ecdc970673c to your computer and use it in GitHub Desktop.
Add support for manipulating specific bits within an integer by treating it like an array of Bool values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source: https://www.douggregor.net/posts/swift-for-cxx-practitioners-extensions/ | |
extension UInt32 { | |
subscript(index: Int) -> Bool { | |
get { | |
(self & UInt32(1) << index) != 0 | |
} | |
set { | |
let mask = UInt32(1) << index | |
self = (self & ~mask) | (newValue ? mask : 0) | |
} | |
} | |
} | |
// Usage | |
var flags: UInt32 = 0b1001 | |
flags[2] = true // set bit #2 | |
flags[0] = false // clear bit #0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment