Skip to content

Instantly share code, notes, and snippets.

@iluvcapra
Created August 6, 2020 23:25
Show Gist options
  • Save iluvcapra/2fe74e449f197ec8c43933330e3e5bde to your computer and use it in GitHub Desktop.
Save iluvcapra/2fe74e449f197ec8c43933330e3e5bde to your computer and use it in GitHub Desktop.
struct Bitfield<Value: FixedWidthInteger> {
let value : Value
func split(widths : [Int]) -> [Value] {
var ranges = [Range<Int>]()
var at = 0
for width in widths {
let thisRange = Range(uncheckedBounds: (lower: at, upper: at + width))
ranges.append(thisRange)
at += width
}
return ranges.map { self[$0] }
}
subscript(bounds : Range<Int>) -> Value {
let mask = Value( (1 << bounds.count) - 1 )
return (value >> bounds.startIndex) & mask
}
subscript(index : Int) -> Value {
return (value >> index) & 0x1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment