Swift Bitwise Operators: &, |, ^, ~, <<, >>, Masks, and Flags

Swift's bitwise operators work on the individual bits of an integer: & keeps the bits that are set in both values, | keeps the bits set in either value, ^ keeps the bits that differ, and ~ flips every bit. The shift operators << and >> move bits left or right, and in Swift they never crash: shifting past the width of the type simply gives 0 (or -1 for a negative signed value). This page shows each operator on real bit patterns, then covers masks and flags, signed and unsigned shifts, the masking shifts &<< and &>>, printing numbers in binary, and when an OptionSet is the better choice.

Difficulty: Intermediate

Helpful to know first: Swift integer types such as Int and UInt8, how binary numbers count (1, 10, 11, 100), and the ordinary arithmetic operators.

How Swift's Bitwise Operators Change the Bits of an Integer

Every Swift integer type has a fixed number of bits. A UInt8 has 8, an Int32 has 32, and Int has 64 on 64-bit platforms such as current Macs and iPhones (Int.bitWidth tells you). The bitwise operators line up two values bit by bit and compute each result bit on its own. Nothing carries from one position to the next, which is what makes them different from + and *.

Binary literals start with 0b, and you can put underscores anywhere in a number to group the bits. The comment block shows the bits; the last line prints the decimal results.

Swift
let a: UInt8 = 0b1100_1010   // 202
let b: UInt8 = 0b1010_0110   // 166

// a       1100 1010
// b       1010 0110
// a & b   1000 0010  = 130
// a | b   1110 1110  = 238
// a ^ b   0110 1100  = 108
// ~a      0011 0101  = 53
print(a & b, a | b, a ^ b, ~a)   // Output: 130 238 108 53
Output✓ Tested · Swift 6.4
130 238 108 53

Read each column from top to bottom. In the first column both bits are 1, so a & b and a | b both keep a 1 and a ^ b gets a 0. The prefix operator ~ takes one value and flips all 8 bits.

OperatorNameA result bit is 1 when…Example on UInt8
&ANDboth bits are 10b1100 & 0b1010 is 0b1000
|ORat least one bit is 10b1100 | 0b1010 is 0b1110
^XORthe two bits differ0b1100 ^ 0b1010 is 0b0110
~NOTthe input bit is 0~0b0000_1111 is 0b1111_0000
<<left shiftbits move toward the high end; zeros fill in on the right0b0000_0011 << 2 is 0b0000_1100
>>right shiftbits move toward the low end0b0000_1100 >> 2 is 0b0000_0011

Each operator also has a compound form that updates a variable in place: &=, |=, ^=, <<= and >>=. The operators exist only for integer types. Using them on a Double or a Bool is a compile error, for example binary operator '&' cannot be applied to two 'Bool' operands; for Booleans use && and ||.

Printing an Integer in Binary with String(_:radix:)

When you debug bit code you want to see the bits. String(value, radix: 2) converts an integer to a binary string, and Int(text, radix: 2) goes the other way. Two details surprise people: leading zeros are dropped, and negative numbers are printed with a minus sign instead of their real bit pattern.

Swift
let value: UInt8 = 0b0000_0101

print(String(value, radix: 2))                  // Output: 101
print(String(-5, radix: 2))                     // Output: -101
print(String(255, radix: 16, uppercase: true))  // Output: FF
print(Int("1011", radix: 2) ?? 0)               // Output: 11
Output✓ Tested · Swift 6.4
101
-101
FF
11

The parsing initializer returns an optional because the text may not be valid binary. To see all the bits, including the two's complement pattern of a negative number, convert to the unsigned type of the same width and pad with zeros. This small generic helper works for every fixed-width integer type:

Swift
func bits<T: FixedWidthInteger>(_ value: T) -> String {
    // Same bits, read as unsigned: negative values show their two's complement
    let raw = String(T.Magnitude(truncatingIfNeeded: value), radix: 2)
    let padding = String(repeating: "0", count: T.bitWidth - raw.count)
    return padding + raw
}

print(bits(UInt8(5)))     // Output: 00000101
print(bits(Int8(-5)))     // Output: 11111011
print(bits(UInt16(240)))  // Output: 0000000011110000
Output✓ Tested · Swift 6.4
00000101
11111011
0000000011110000

T.Magnitude is the unsigned type with the same width (UInt8 for Int8), and truncatingIfNeeded: copies the bit pattern without any range check. Do not use the magnitude property here: Int8(-5).magnitude is 5, not the bits of -5. For one known type, UInt8(bitPattern: someInt8) does the same reinterpretation.

Masks and Flags: Testing, Setting, Clearing, and Extracting Bits

A mask is an integer whose 1 bits mark the positions you care about. Combine a value with a mask and you can read, set, clear or flip exactly those bits and leave the rest alone. The examples go from a single bit to real packed formats.

Testing whether one bit is set

To test bit number 2, build a mask with only that bit (1 << 2), AND it with the value, and compare the result with zero.

Swift
let flags: UInt8 = 0b0000_0110
let bit2: UInt8 = 1 << 2          // 0b0000_0100

let isSet = (flags & bit2) != 0
print(isSet)                      // Output: true
print(flags & 0b0000_0001 != 0)   // Output: false
Output✓ Tested · Swift 6.4
true
false

AND clears every bit outside the mask, so the result is either 0 or the mask itself. The last line has no parentheses and still means (flags & 1) != 0, because in Swift & binds tighter than !=. In C the same line would be parsed the other way. Parentheses make the intent obvious to every reader, so keep them in real code.

Setting, clearing, and toggling permission flags

Give each flag its own bit, and one small integer can store many yes/no settings. OR sets a bit, AND with the inverted mask clears it, and XOR flips it.

Swift
let canRead: UInt8 = 1 << 0     // 0b001
let canWrite: UInt8 = 1 << 1    // 0b010
let canDelete: UInt8 = 1 << 2   // 0b100

var permissions: UInt8 = canRead

permissions |= canWrite     // set:    0b011
permissions |= canDelete    // set:    0b111
permissions &= ~canWrite    // clear:  0b101
permissions ^= canRead      // toggle: 0b100

print(permissions)                     // Output: 4
print(permissions & canDelete != 0)    // Output: true
Output✓ Tested · Swift 6.4
4
true

The clearing line is the one to remember. ~canWrite is 0b1111_1101: every bit except the write bit. ANDing with it switches off the write bit and keeps the others as they were.

Extracting fields from a packed header

Binary formats often pack several small numbers into one integer. To read a field, shift it down to bit 0, then AND with a mask that is as wide as the field. A run of n one bits is (1 << n) - 1.

Swift
// Layout: version (4 bits) | kind (4 bits) | length (8 bits)
let header: UInt16 = 0b0010_0101_0001_1000

let lowByte: UInt16 = (1 << 8) - 1     // 0b1111_1111
let version = header >> 12             // top 4 bits
let kind = (header >> 8) & 0b1111      // next 4 bits
let length = header & lowByte          // low 8 bits

print(version, kind, length)   // Output: 2 5 24
Output✓ Tested · Swift 6.4
2 5 24

The version needs no mask, because shifting right by 12 already removes everything below it. Writing the layout in a comment next to the code saves the next reader from decoding the masks by hand.

Packing and unpacking an RGB color

A 24-bit color stores red, green and blue as three bytes in one UInt32. Packing is shift-then-OR; unpacking is shift-then-truncate.

Swift
let red: UInt8 = 255
let green: UInt8 = 136
let blue: UInt8 = 0

// Widen to UInt32 first, then shift
let color = UInt32(red) << 16 | UInt32(green) << 8 | UInt32(blue)
print(String(color, radix: 16))   // Output: ff8800

let r = UInt8(truncatingIfNeeded: color >> 16)
let g = UInt8(truncatingIfNeeded: color >> 8)
let b = UInt8(truncatingIfNeeded: color)
print(r, g, b)                    // Output: 255 136 0
Output✓ Tested · Swift 6.4
ff8800
255 136 0

Because << binds tighter than |, the packing line needs no parentheses. UInt8(truncatingIfNeeded:) keeps the low 8 bits, which does the job of & 0xFF. A plain UInt8(color >> 8) would stop the program, because 0xFF88 does not fit in a byte; a debug build reports Fatal error: Not enough bits to represent the passed value.

Counting set bits and checking for a power of two

You rarely need loops over bits. Every fixed-width integer has properties for counting them, and the classic n & (n - 1) trick clears the lowest set bit.

Swift
let mask: UInt16 = 0b0000_0100_1011_0000

print(mask.nonzeroBitCount)       // Output: 4
print(mask.trailingZeroBitCount)  // Output: 4
print(mask.leadingZeroBitCount)   // Output: 5

func isPowerOfTwo(_ n: Int) -> Bool {
    n > 0 && n & (n - 1) == 0
}
print(isPowerOfTwo(64), isPowerOfTwo(96))   // Output: true false
Output✓ Tested · Swift 6.4
4
4
5
true false

A power of two has exactly one bit set, so clearing its lowest set bit leaves zero. 96 is 0b110_0000; clearing the lowest bit leaves 0b100_0000, which is not zero. n.nonzeroBitCount == 1 gives the same answer for positive numbers and reads more plainly.

How Shifts Behave: Signed Values, Big Shift Amounts, and Precedence

Shifts are where Swift differs most from C and from what people guess. These five rules cover almost every surprise.

Signed right shifts copy the sign bit

On unsigned types, >> fills the top with zeros (a logical shift). On signed types it copies the sign bit into the top (an arithmetic shift), so a negative number stays negative. Shifting -8 (1111_1000) right by one gives 1111_1100, which is -4.

Swift
let negative: Int8 = -8

print(negative >> 1)       // Output: -4
print(Int8(-1) >> 7)       // Output: -1

// Zero-fill shift of a signed value: shift its bit pattern instead
let logical = UInt8(bitPattern: negative) >> 1
print(logical)             // Output: 124
Output✓ Tested · Swift 6.4
-4
-1
124

An arithmetic shift right by n divides by 2n and rounds toward negative infinity, so -7 >> 1 is -4 while -7 / 2 is -3. If you need zero-fill on a signed value, shift its unsigned bit pattern, as in the last line.

Shifting by the bit width or more: smart shifts

In C, shifting a 32-bit value by 32 or more is undefined behavior. Swift's << and >> are "smart shifts" with a defined answer for every amount: overshifting gives 0, or -1 for a negative signed value shifted right, and a negative amount shifts the other way.

Swift
let one: UInt8 = 1
let minus: Int8 = -128

print(one << 7)          // Output: 128
print(one << 8)          // Output: 0
print(minus >> 10)       // Output: -1
print(UInt8(8) << -1)    // Output: 4
Output✓ Tested · Swift 6.4
128
0
-1
4

The shift amount can be any integer type: someUInt8 << someInt compiles without a conversion. Only the value being shifted decides the result type.

Masking shifts: &<< and &>>

The operators &<< and &>> first reduce the shift amount modulo the bit width, then shift. On a UInt8, a shift by 8 becomes a shift by 0 and a shift by 9 becomes a shift by 1. They need no extra handling for oversized or negative amounts, which is why hashing and cryptography code uses them, and they are the natural way to write a bit rotation.

Swift
let one: UInt8 = 1
print(one &<< 8)           // Output: 1
print(one &<< 9)           // Output: 2
print(Int8(-128) &>> 9)    // Output: -64

func rotateLeft(_ x: UInt8, by n: UInt8) -> UInt8 {
    x &<< n | x &>> (8 &- n)
}
print(rotateLeft(0b1000_0001, by: 1))   // Output: 3
print(rotateLeft(0b1000_0001, by: 0))   // Output: 129
Output✓ Tested · Swift 6.4
1
2
-64
3
129

A rotation moves the bits that fall off one end back in at the other. With n equal to 0, the right half becomes x &>> 8, which the mask turns into a shift by 0, so the function returns x unchanged. The &- is wrapping subtraction, one of the Swift overflow operators.

Left shifts drop bits instead of trapping

Ordinary arithmetic in Swift stops the program when a result does not fit. Shifts never do: bits that move past the top are simply lost, even when that changes the sign.

Swift
func doubled(_ x: Int8) -> Int8 {
    x << 1   // x * 2 would stop the program for 100
}
print(doubled(100))   // Output: -56
Output✓ Tested · Swift 6.4
-56

100 is 0110_0100. Shifted left it becomes 1100_1000, which an Int8 reads as -56. So x << 1 is not a safe replacement for x * 2; it is a different operation that silently wraps.

Precedence is not the same as in C

Swift puts the shift operators above multiplication, & at the same level as *, and | and ^ at the same level as +. All of them bind tighter than comparisons.

Swift
print(1 << 2 + 1)      // Output: 5
print(1 << (2 + 1))    // Output: 8
print(6 & 3 == 2)      // Output: true
Output✓ Tested · Swift 6.4
5
8
true

In C, 1 << 2 + 1 is 8 and 6 & 3 == 2 is 0. When you port C or JavaScript bit code to Swift, add parentheses rather than trusting the original layout. The full table of precedence groups is in Swift operator precedence.

Predict the Output

Snippet 1. What does this print?

Swift
let x = 5
print(~x)
print(String(UInt8(~x & 0xFF), radix: 2))
Show answer

It prints -6 and then 11111010.

x is an Int, a signed 64-bit type. Flipping all 64 bits of 5 gives the two's complement pattern of -6 (in general ~n equals -n - 1 for signed integers). Masking with 0xFF keeps only the low byte, 1111_1010, which is 250 and fits in a UInt8.

Snippet 2. What does this print?

Swift
let small: UInt8 = 0b0000_0001
let negative: Int8 = -16

print(small << 8, small &<< 8)
print(negative >> 2, negative >> 100)
Show answer

It prints 0 1 and then -4 -1.

small << 8 pushes the only 1 bit out of the byte, so the result is 0. small &<< 8 masks the amount first: 8 modulo 8 is 0, so the value is unchanged. -16 shifted right by 2 is an arithmetic shift, giving -4. Shifting a negative signed value right by more than its width fills every bit with the sign bit, which is -1.

Common Mistakes with Bitwise Operators in Swift

Mixing integer types in one bitwise expression

An integer literal without a type annotation becomes an Int. Combine that constant with a UInt8 and Swift refuses, because it never converts integer types silently.

Problem: errorBit is inferred as Int, so the AND has two different operand types. The compiler reports: binary operator '&' cannot be applied to operands of type 'UInt8' and 'Int'.

Swift
let status: UInt8 = 0b0000_1010
let errorBit = 0b0000_0010

if status & errorBit != 0 {
    print("error flag set")
}
Compiler output✓ Tested · Swift 6.4
error: binary operator '&' cannot be applied to operands of type 'UInt8' and 'Int'

Fix: Give the mask the same type as the value it is used with.

Swift
let status: UInt8 = 0b0000_1010
let errorBit: UInt8 = 0b0000_0010

if status & errorBit != 0 {
    print("error flag set")   // Output: error flag set
}
Output✓ Tested · Swift 6.4
error flag set

The corrected version compiles because both operands of & are now UInt8; only the shift amount of << and >> may have a different type.

Shifting a byte before widening it

When you build a larger value from bytes, the shift has to happen in the larger type. A UInt8 shifted by 8 or more places is always 0.

Problem: red << 16 is computed as a UInt8, so every bit falls off and the result is 0 before the conversion to UInt32 happens. There is no error and no warning; the color is just black.

Swift
let red: UInt8 = 255
let green: UInt8 = 136

let color = UInt32(red << 16) | UInt32(green << 8)
print(String(color, radix: 16))   // Output: 0
Output✓ Tested · Swift 6.4
0

Fix: Convert each byte to the wide type first, then shift.

Swift
let red: UInt8 = 255
let green: UInt8 = 136

let color = UInt32(red) << 16 | UInt32(green) << 8
print(String(color, radix: 16))   // Output: ff8800
Output✓ Tested · Swift 6.4
ff8800

The corrected version works because a UInt32 has room for bits shifted 16 places.

Comparing a masked value with 1

After value & mask, the result is either 0 or the mask itself. It is 1 only when the mask is bit 0.

Problem: The delete bit is bit 2, so flags & deleteBit is 4 when the flag is set. Comparing with 1 is false whether the flag is set or not.

Swift
let flags: UInt8 = 0b0000_0100
let deleteBit: UInt8 = 1 << 2

print((flags & deleteBit) == 1)   // Output: false
Output✓ Tested · Swift 6.4
false

Fix: Compare the masked value with zero.

Swift
let flags: UInt8 = 0b0000_0100
let deleteBit: UInt8 = 1 << 2

print((flags & deleteBit) != 0)   // Output: true
Output✓ Tested · Swift 6.4
true

The corrected check works for a mask at any bit position, because a set bit makes the result non-zero.

Reading String(_:radix:) as the raw bits

String(_:radix:) writes the number's value in base 2, not its storage. For a negative signed value that is a minus sign plus the magnitude.

Problem: A sensor reading of -3 prints as -11, which is not what the byte on the wire looks like, so a debug log built this way hides the real bit pattern.

Swift
let reading: Int8 = -3
print(String(reading, radix: 2))   // Output: -11
Output✓ Tested · Swift 6.4
-11

Fix: Reinterpret the value as the unsigned type of the same width before formatting it.

Swift
let reading: Int8 = -3
print(String(UInt8(bitPattern: reading), radix: 2))   // Output: 11111101
Output✓ Tested · Swift 6.4
11111101

The corrected version prints the two's complement byte, because UInt8(bitPattern:) keeps the bits and only changes how they are read.

Find the Bug

This helper is meant to take a permission away from a user. It passes a quick test where the user had the permission. Find the case where it does the opposite of what its name says.

Swift
let read: UInt8 = 1 << 0
let write: UInt8 = 1 << 1
let share: UInt8 = 1 << 2

// Remove a permission from a set of flags
func revoke(_ permission: UInt8, from flags: UInt8) -> UInt8 {
    flags ^ permission
}

let viewer = read | share
let updated = revoke(write, from: viewer)
print(updated & write != 0)
Show answer

It prints true: revoking write access from a viewer who never had it grants it. XOR toggles bits. It clears the bit when it is set, but sets it when it is clear, so the function only works when the user already has the permission.

To clear a bit no matter what its current state is, AND with the inverted mask:

Swift
let read: UInt8 = 1 << 0
let write: UInt8 = 1 << 1
let share: UInt8 = 1 << 2

func revoke(_ permission: UInt8, from flags: UInt8) -> UInt8 {
    flags & ~permission
}

let viewer = read | share
let updated = revoke(write, from: viewer)
print(updated & write != 0)   // Output: false
Output✓ Tested · Swift 6.4
false

Use XOR only when you really mean "flip", such as a toggle button or a checksum.

When to Use OptionSet Instead of Raw Bit Masks

Raw masks are the right tool when the bits come from outside your program: a file header, a network packet, a hardware register, a hash function. For flags that only your own code uses, an OptionSet stores the same bits but gives them a type and set-style methods, so the Find the Bug mistake above cannot happen.

Swift
struct Permissions: OptionSet {
    let rawValue: UInt8

    static let read = Permissions(rawValue: 1 << 0)
    static let write = Permissions(rawValue: 1 << 1)
    static let share = Permissions(rawValue: 1 << 2)
}

var viewer: Permissions = [.read, .share]
viewer.remove(.write)             // safe even when .write is absent
print(viewer.contains(.write))    // Output: false
print(viewer.rawValue)            // Output: 5
Output✓ Tested · Swift 6.4
false
5

Under the hood remove does the & ~ for you, and rawValue is still a plain UInt8 you can store or send. You cannot pass a stray Int where a Permissions value is expected. The full guide, including grouped options and raw value design, is in Swift OptionSet.

ChooseWhen
Raw masks on UInt8, UInt16, …The bit layout is fixed by a file format, protocol, or hardware; hashing and checksums
OptionSetYour own combinable flags that should be compact and type-safe
Set of an enumOptions that do not need a compact binary form, or more than 64 of them
Separate Bool propertiesA few unrelated settings that are never combined or stored as one number

Integer widths and the exact range of each type are covered in Swift data types.

Interview Questions About Swift Bitwise Operators

How do you check whether an integer is a power of two?

Check n > 0 && n & (n - 1) == 0. Subtracting 1 flips the lowest set bit and every zero below it, so the AND is zero only when exactly one bit was set. n.nonzeroBitCount == 1 says the same thing more directly for positive values.

How does >> differ between Int and UInt?

On UInt it is a logical shift: zeros enter from the top. On Int it is an arithmetic shift: copies of the sign bit enter from the top, so negative values stay negative. To get a zero-fill shift of a signed value, shift UInt(bitPattern: value).

What happens if you shift by more than the bit width?

With << and >> the result is fully defined: 0 for left shifts and unsigned right shifts, and 0 or -1 for signed right shifts depending on the sign. Negative amounts shift the other way. With &<< and &>>, the amount is first reduced modulo the bit width. Neither form crashes, unlike the undefined behavior of oversized shifts in C.

Try It Yourself

Small displays often store colors as RGB565: 5 bits of red, 6 bits of green and 5 bits of blue in one UInt16, with red in the top bits.

  • Write pack565(red:green:blue:) that takes three UInt8 channels (0–255) and keeps the top 5, 6 and 5 bits of each.
  • Write unpack565(_:) that returns the three fields as a tuple of UInt8 values (red 0–31, green 0–63, blue 0–31).
  • Pack the orange color (255, 136, 0), print the packed value in hexadecimal, then unpack it and print the fields.

Expected output: fc40 on the first line, then 31 34 0.

Hint: Shift each channel right to drop its low bits, widen it to UInt16, then shift it left into place (red by 11, green by 5). To unpack, shift down and AND with 0b1_1111 or 0b11_1111.

Show solution
Swift
func pack565(red: UInt8, green: UInt8, blue: UInt8) -> UInt16 {
    let r = UInt16(red >> 3)     // 5 bits
    let g = UInt16(green >> 2)   // 6 bits
    let b = UInt16(blue >> 3)    // 5 bits
    return r << 11 | g << 5 | b
}

func unpack565(_ color: UInt16) -> (red: UInt8, green: UInt8, blue: UInt8) {
    let r = UInt8(color >> 11)
    let g = UInt8((color >> 5) & 0b11_1111)
    let b = UInt8(color & 0b1_1111)
    return (r, g, b)
}

let orange = pack565(red: 255, green: 136, blue: 0)
print(String(orange, radix: 16))              // Output: fc40

let fields = unpack565(orange)
print(fields.red, fields.green, fields.blue)  // Output: 31 34 0
Output✓ Tested · Swift 6.4
fc40
31 34 0

Summary

  • &, |, ^ and ~ work bit by bit on integers of the same type: AND tests and clears, OR sets, XOR flips, NOT inverts.
  • Test a flag with (value & mask) != 0, set it with |=, and clear it with &= ~mask; XOR only when you mean "toggle".
  • >> is arithmetic on signed types and logical on unsigned types; shift the bitPattern when you need zero-fill.
  • Smart shifts never crash: overshifting gives 0 or -1, and negative amounts reverse direction. &<< and &>> reduce the amount modulo the bit width.
  • Swift's precedence differs from C: shifts bind tighter than + and *, and & binds tighter than ==.
  • String(_:radix:) drops leading zeros and prints negatives with a minus sign; convert through the unsigned type to see the real bits.

Bit tricks and wrapping arithmetic often appear together in hashes and checksums. Next, read Swift overflow operators to see how &+ and &* wrap instead of trapping, and why ordinary + stops the program.