Skip to content

Bits

Integers have & (and), | (or), ^ (exclusive or), << and >> (shifts) and !x (every bit flipped); numbers can be written 0xff, 0b1010_0101 or 0o755. Both sides of &, |, ^ have the same type; a shift takes any integer as its amount and keeps the type of the value. >> keeps the sign for signed types and fills with zeros for unsigned ones, and << drops bits shifted out. Shifting by a negative amount or by the type’s width or more stops the program, as overflow does (in C it is undefined). bool has no bit operators: &&, || and != say it.

Their order of precedence is the one people misremember, so mixing needs parentheses: (x & 1) == 0, a | (b & c), 1 << (n - 1), (x >> 2) > 3. Only the same bitwise operator repeats freely (a | b | c).

count_ones(), leading_zeros(), trailing_zeros() (all i64) and rotate_left(n) / rotate_right(n) (any n, taken modulo the width) work on every integer type.