typestar

Bitwise operations in Mojo

Shifts and masks are how flags, hashes, and packed formats get handled.

def main():
    var flags = 0b1011
    print(bin(flags), hex(flags))
    print(flags << 3, flags >> 1)
    print(flags & 0b0110, flags | 0b0100, flags ^ 0b1111)
    print(flags & ~0b0010)

How it works

  1. bin and hex print the same integer in two bases.
  2. << and >> slide the bits left and right.
  3. &, |, ^, and ~ combine and invert bit patterns.

Keywords and builtins used here

The run, in numbers

Lines
6
Characters to type
167
Tokens
48
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 36 seconds.

Type this snippet

Step 4 of 5 in Numbers & time, step 15 of 22 in Parameters & SIMD.

← Previous Next →