Last active
June 27, 2022 20:47
-
-
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.
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
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