Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Bitwise Operators

OperatorNameExample
&Bitwise ANDa & b
|Bitwise ORa | b
^Bitwise XORa ^ b
~Bitwise NOT~a
<<Left shifta << b
>>Right shifta >> b

All operators work with every integer type. >> is arithmetic for signed types, logical for unsigned types.

Example

pub fn get_bit(x: i32, pos: i32) -> i32 {
    return (x >> pos) & 1;
}

pub fn set_bit(x: i32, pos: i32) -> i32 {
    return x | (1 << pos);
}

pub fn clear_bit(x: i32, pos: i32) -> i32 {
    return x & ~(1 << pos);
}

pub fn is_power_of_two(n: i32) -> bool {
    if n <= 0 {
        return false;
    }
    return (n & (n - 1)) == 0;
}