Skip to content

Instantly share code, notes, and snippets.

@ducaale
Last active December 29, 2022 18:34
Show Gist options
  • Save ducaale/adad7c4fb7fc17552f960a851c4ff8f3 to your computer and use it in GitHub Desktop.
Save ducaale/adad7c4fb7fc17552f960a851c4ff8f3 to your computer and use it in GitHub Desktop.
Bit manipulation in Rust
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);
}
@ducaale
Copy link
Author

ducaale commented Dec 29, 2022

Another interesting approach to extract bit (from Nand2Tetris discussions):

  1. turn off every bit except the one we want to extract
  2. check if the result is zero or not
let masks = [
  0000_0001,
  0000_0010,
  0000_0100,
  ...
];

x & masks[i] == 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment