Last active
December 29, 2022 18:34
-
-
Save ducaale/adad7c4fb7fc17552f960a851c4ff8f3 to your computer and use it in GitHub Desktop.
Bit manipulation in Rust
This file contains 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() { | |
// format a number in two’s complement representation | |
let a: i8 = -1; | |
assert_eq!(format!("{:b}", a), "11111111"); | |
// concatenate 3 bit slices | |
let b: i8 = (0b10 << 4) + (0b10 << 2) + (0b10); | |
assert_eq!(b, 0b101010); | |
// get bit at index 5 (counting from right) | |
let index = 5; | |
let c: bool = (0b101010 >> index) & 1 == 1; | |
assert_eq!(c, true); | |
// get a bit slice (indices counting from right) | |
let (start, end) = (3, 6); | |
let mask = !(-1 << (end - start)); | |
let d: i8 = (0b101010 >> start) & mask; | |
assert_eq!(d, 0b101); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another interesting approach to extract bit (from Nand2Tetris discussions):