Created
November 13, 2019 15:56
-
-
Save BigZaphod/eb8b07a5fe5a1aa96be290dfa7457711 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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