Skip to content

Instantly share code, notes, and snippets.

@BixinFromThisRealm
Last active June 27, 2022 20:47
Show Gist options
  • Save BixinFromThisRealm/e3a98793fc067271b5e67021592f19ce to your computer and use it in GitHub Desktop.
Save BixinFromThisRealm/e3a98793fc067271b5e67021592f19ce to your computer and use it in GitHub Desktop.
A tiny but useful algorithm for getting the bits from n to k off a integer.
fn main() {
let num = slice(0b1101001, 3, 7);
println!("num = {:#b}", num); // "num = 0b1101"
}
// since all this is just some basic arithmetic
// the function should have a big O of 1.
fn slice(bits: i32, start: i32, end: i32) -> i32 {
assert!(end > start, "end bit is smaller or equal to the start!");
let diff = end - start;
let mask = (1 << diff) - 1;
(bits >> start) & mask
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment