2021-07-06

Bitwise cheat sheet for Rust

Operators

AND         &
OR          |
NOT         !
XOR         ^
Left shift  <<
Right shift >>

Get a bit

(i >> n) & 1

Set a bit

Set to 1

i | (1 << n)

Set to 0

i & !(1 << n)

Toggle a bit

i ^ (1 << n)

Source: https://nicolwk.medium.com/bitwise-operations-cheat-sheet-743e09aec5b5

Examples

Clearing bits

Note that the following examples produce the same asm.

Bit mask

let mask = 0b00001111;
let value = 0b1110101;
let result = mask & value;
assert_eq!(result, 0b00000101);

Shifting twice

Clearing half a byte by shifting all bits to the left and then back.

let value: u8 = 0b1110101;
let result = value << 4 >> 4;
assert_eq!(result, 0b00000101);

To clear the other half, change << 4 >> 4 to >> 4 << 4.