Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 146 ยท Standard Library and Foundation

Bitwise and Overflow Operators

Learn Swift bitwise operators, shifts, masks and flags, bit counting, two's complement, wrapping &+ &- &* operators, truncatingIfNeeded, OptionSet and a small FNV hash.

Every integer is stored as a row of bits. Most code never looks at them, but some jobs are about nothing else: packing several yes/no settings into one number, reading the fields of a binary file header, writing a checksum or a hash, talking to hardware, or squeezing a color into 32 bits. For those jobs Swift gives you the bitwise operators (&, |, ^, ~, <<, >>) and the overflow operators (&+, &-, &*, &<<, &>>).

You met the headline versions in operators and numbers. This lesson goes deeper: how to print and read the bits, the standard bit tricks, what two's complement means for negative numbers, how to convert between integer sizes without a trap, and how Swift's OptionSet wraps all of this in a safe, readable type. Every example is deterministic and runs here.

Seeing the bits

To reason about bits you need to see them. String(value, radix: 2) prints a number in binary, and a small helper pads it to the type's width:

Swift Printing binary with padding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first three lines are the plain binary forms. The Int8(-5) line shows why the helper above is only half the story: it prints the magnitude, so -5 looks like 5. To see the real stored bits of a signed number, reinterpret it as unsigned with UInt8(bitPattern:), which is what the last line does. Remember this: bitPattern: keeps the bits and changes the meaning.

The six bitwise operators

All of them work on integers, bit by bit. The names to remember are AND (keep bits that are on in both), OR (keep bits on in either), XOR (keep bits that differ), NOT (flip every bit), and the two shifts.

flowchart TB
    subgraph A["a = 0b1100  b = 0b1010"]
    end
    A --> AND["a AND b = 0b1000"]
    A --> OR["a | b = 0b1110"]
    A --> XOR["a ^ b = 0b0110"]
    A --> NOT["~a = 0b0011 (4 bits)"]

Each result bit depends only on the two input bits in the same column.

Swift AND, OR, XOR, NOT and shifts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Compare each column: x & y has a 1 only where both inputs have one; x | y where either does; x ^ y where they differ; ~x flips all eight bits. Shifting left by 2 moves every bit two places up and fills with zeros, and the two top bits fall off. Shifting right does the opposite.

Shifts are "smart" in Swift

In C, shifting by the width of the type or more is undefined. Swift defines it. A normal shift treats the count as a plain number: shifting by the width or more gives 0 (or -1 for a negative signed value shifted right), and a negative count shifts the other way. If you want the raw hardware behavior where the count is masked to the bit width, use the masking shifts &<< and &>>.

Swift Smart shifts versus masking shifts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Right shifts of signed integers copy the sign bit in from the left (an arithmetic shift), which is why -8 >> 1 is -4 and a very large shift gives -1. Right shifts of unsigned integers fill with zeros. Use unsigned types when you are treating a value as a bag of bits, and signed types when it is a number.

Masks, flags and the standard tricks

A mask is a number whose set bits select the bits you care about. With one & you read, with | you set, with & ~ you clear and with ^ you toggle:

Swift Set, clear, toggle and test bits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Read the pattern: test with flags & mask != 0, set with flags |= mask, clear with flags &= ~mask, toggle with flags ^= mask. Parentheses matter in Swift: & has multiplication precedence, so flags & isVisible != 0 is parsed as you expect (& first), unlike C where the comparison binds tighter. When in doubt, add parentheses anyway.

Counting and finding bits

Integers have properties for the most common queries, all compiled to a single CPU instruction on modern hardware:

Swift popcount, leading and trailing zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

nonzeroBitCount is the "population count", leadingZeroBitCount and trailingZeroBitCount help find the highest and lowest set bits. byteSwapped reverses the bytes, which is how you convert between big-endian and little-endian when parsing binary data (see data and bytes).

A few classic tricks, all for unsigned or non-negative values:

  • Is a power of two? n != 0 && n & (n - 1) == 0. Subtracting 1 flips the lowest set bit and the zeros below it, so the AND clears exactly that bit.
  • Lowest set bit: n & (~n &+ 1) isolates it (the &+ avoids a trap for n == 0).
  • Swap without a temporary: a ^= b; b ^= a; a ^= b works but is mostly a curiosity; use swap(&a, &b).
  • Fast multiply or divide by 2^k: n << k and n >> k. The optimizer does this for you when you write n * 8, so write what you mean.

Two's complement

Signed integers use two's complement: to negate, flip all bits and add one. The top bit is the sign. That is why Int8 runs from -128 to 127 and why Int8(-5) has the bits 11111011. It also explains the surprise that abs(Int8.min) has no positive partner: -128 negated is 128, which does not fit.

Swift Two's complement and conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The four ways to change integer size answer four different questions, so pick deliberately:

Initializer Result for 300 into UInt8 Use it when
UInt8(300) crash You are sure it fits
UInt8(exactly: 300) nil You want to detect that it does not fit
UInt8(clamping: 300) 255 Saturating is the right behavior
UInt8(truncatingIfNeeded: 300) 44 You want the low bits (hashing, byte extraction)

The overflow operators

Normal +, -, * trap on overflow (see operators). The overflow operators wrap around instead, using the same bit rules as hardware. Choose them when wrap-around is the specification: hashes, random generators, checksums, sequence counters, ring buffers.

Operator Meaning
a &+ b add, wrapping
a &- b subtract, wrapping
a &* b multiply, wrapping
a &<< n, a &>> n shift with the count masked to the bit width

When you need to know whether it overflowed, use the ...ReportingOverflow methods, and for the full double-width result of a multiply use multipliedFullWidth(by:):

Swift Wrapping, reporting and full-width multiply

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

255 &+ 1 is 0, 0 &- 1 is 255, and the signed version wraps from 127 to -128. The reporting version returns the wrapped value together with a flag. multipliedFullWidth never loses information: UInt64.max * 2 is 2^65 - 2, shown as high = 1 and low = 18446744073709551614. The last two lines show the classic edge case: Int8.min.magnitude is 128 (as a UInt8) but Int8.min &* -1 wraps back to -128.

A real example: FNV-1a hashing

A hash is a function that scrambles bytes into a fixed-size number. FNV-1a is tiny and a good fit for the overflow operators: it XORs each byte in, then multiplies by a prime, expecting the multiplication to wrap.

Swift FNV-1a hash with wrapping multiply

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

With plain * this program would trap on the first long word. The mask at the end is the other classic trick: when the table size is a power of two, hash & (size - 1) is a fast hash % size. (Swift's own Hashable is randomized per run for security, so do not use hashValue for anything that must be stable; write your own function like this one when you need a stable value.)

OptionSet: flags with safe names

Doing flag math by hand works but is easy to get wrong. The standard library packages it as the OptionSet protocol: a struct wrapping a rawValue integer, with static members for each flag. You get contains, insert, remove, union, intersection and array-literal syntax for free.

Swift An OptionSet for permissions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The printed numbers are 3 for read plus write, true false for contains, and so on. OptionSet is a Set-like abstraction on top of the same masks you wrote by hand, so you can still store the rawValue in a file or send it over a network. Define a new flag by choosing the next free power of two, and never reuse or reorder values once they are persisted.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which expression clears the bit selected by mask in flags?

    ~mask has zeros where the flag is and ones elsewhere, so ANDing keeps every other bit and clears the selected one.
  2. 2. What does UInt8(truncatingIfNeeded: 300) return?

    300 is 0b1_0010_1100. Keeping the low eight bits gives 0b0010_1100, which is 44.
  3. 3. What is UInt8.max &+ 1?

    The &+ operator wraps around, so the largest UInt8 plus one becomes zero. The ordinary + would trap.
  4. 4. Why is Int8.min &* -1 equal to -128?

    Two's complement has one more negative value than positive, so negating the minimum wraps back to itself.
  5. 5. What is one << 8 for let one: UInt8 = 1?

    Swift defines over-shifts: all bits are shifted out, leaving 0. The masking shift &<< would mask the count and return 1.

Summary

  • Use &, |, ^, ~, <<, >> on integers; prefer unsigned types for bit work and print bits with String(value, radix: 2).
  • Test with flags & mask != 0, set with |=, clear with &= ~mask, toggle with ^=.
  • Smart shifts are defined for any count; &<< and &>> mask the count like hardware.
  • nonzeroBitCount, leadingZeroBitCount, trailingZeroBitCount and byteSwapped replace hand-written loops.
  • Signed integers use two's complement; convert sizes with exactly, clamping or truncatingIfNeeded depending on what you mean.
  • &+, &-, &* wrap instead of trapping; ReportingOverflow and multipliedFullWidth keep the extra information.
  • OptionSet is the safe, named wrapper for flag masks.

Next: Memory Layout