Skip to content

Instantly share code, notes, and snippets.

@BigZaphod
Created November 13, 2019 15:56
Show Gist options
  • Save BigZaphod/eb8b07a5fe5a1aa96be290dfa7457711 to your computer and use it in GitHub Desktop.
Save BigZaphod/eb8b07a5fe5a1aa96be290dfa7457711 to your computer and use it in GitHub Desktop.
extension BinaryInteger {
subscript(bit index: Int) -> Bool {
get {
((self >> index) & Self(1)) == 1
}
set {
if newValue {
self |= (Self(1) << index)
} else {
self &= ~(Self(1) << index)
}
}
}
subscript(bits range: ClosedRange<Int>) -> Int {
get {
Int((~(~Self(0) << range.count)) & (self >> range.lowerBound))
}
set {
let clampedAndShiftedValue = (((~(~Self(0) << range.count)) & Self(clamping: newValue)) << range.lowerBound)
let shiftedMask = ~(~Self(0) << range.count) << range.lowerBound
let selfWithBitRangeSetToZero = (~(self & shiftedMask) & self)
self = selfWithBitRangeSetToZero | clampedAndShiftedValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment