Pack Eight Flags Into One Byte

Store eight boolean flags in a single u8 with shift and mask operations, then read, set, clear, and toggle individual bits without any allocation.

RustData Integrity

Code

rustsnippet
22 lines
fn main() {
    // 一个 u8 打包 8 个布尔位:bit 0 = read, bit 1 = write, bit 2 = exec
    let mut perms: u8 = 0;

    // set:按位或上对应掩码
    let (read, write, exec) = (0b001, 0b010, 0b100);
    perms |= read | exec;
    println!("after set read+exec: {:03b}", perms);

    // get:与上掩码,非零即置位
    let has = |flag: u8| (perms & flag) != 0;
    println!("read={} write={} exec={}", has(read), has(write), has(exec));

    // clear:按位与非
    perms &= !exec;
    println!("after clear exec: {:03b}", perms);

    // toggle:异或翻转
    perms ^= write;
    perms ^= write;
    println!("after toggle twice: {:03b}", perms);
}

How the snippet works

The working surface is the function main — everything else is wiring.

Points of care

  • No external packages — everything relies on the language’s built-in APIs.

Applying it

The main signature reads fn main()

Expect labeled output — after set read+exec:, read=, after clear exec: — when the file runs.

Statements that matter

let (read, write, exec) = (0b001, 0b010, 0b100);
let has = |flag: u8| (perms & flag) != 0;
let mut perms: u8 = 0;

Interactive Tools for This Topic

FAQ

What does Pack Eight Flags Into One Byte print when run?
Execute the whole file; each printed line is prefixed with a label like `after set read+exec:`, `read=`, `after clear exec:`.