位运算符 #

一、位运算符概述 #

位运算符直接对整数在内存中的二进制位进行操作。Swift支持以下位运算符:

运算符 名称 描述
& 按位与 两位都为1才为1
| 按位或 有一位为1就为1
^ 按位异或 两位不同为1
~ 按位取反 0变1,1变0
<< 左移 左移指定位数
>> 右移 右移指定位数

二、按位与(&) #

2.1 基本用法 #

swift
let a: UInt8 = 0b10101010
let b: UInt8 = 0b11001100

let result = a & b
print(String(result, radix: 2))

2.2 真值表 #

a b a & b
0 0 0
0 1 0
1 0 0
1 1 1

2.3 实际应用 #

掩码操作 #

swift
let flags: UInt8 = 0b00001111
let mask: UInt8 = 0b00000101

let result = flags & mask
print(String(result, radix: 2))

检查特定位 #

swift
let value: UInt8 = 0b00001010

func isBitSet(_ value: UInt8, _ position: Int) -> Bool {
    let mask: UInt8 = 1 << position
    return (value & mask) != 0
}

print(isBitSet(value, 1))
print(isBitSet(value, 2))
print(isBitSet(value, 3))

三、按位或(|) #

3.1 基本用法 #

swift
let a: UInt8 = 0b10101010
let b: UInt8 = 0b11001100

let result = a | b
print(String(result, radix: 2))

3.2 真值表 #

a b a | b
0 0 0
0 1 1
1 0 1
1 1 1

3.3 实际应用 #

设置标志位 #

swift
var permissions: UInt8 = 0b00000000

let readPermission: UInt8 = 0b00000001
let writePermission: UInt8 = 0b00000010
let executePermission: UInt8 = 0b00000100

permissions = permissions | readPermission | writePermission
print(String(permissions, radix: 2))

四、按位异或(^) #

4.1 基本用法 #

swift
let a: UInt8 = 0b10101010
let b: UInt8 = 0b11001100

let result = a ^ b
print(String(result, radix: 2))

4.2 真值表 #

a b a ^ b
0 0 0
0 1 1
1 0 1
1 1 0

4.3 实际应用 #

切换位 #

swift
var flags: UInt8 = 0b00001010
let toggleMask: UInt8 = 0b00000100

flags = flags ^ toggleMask
print(String(flags, radix: 2))

flags = flags ^ toggleMask
print(String(flags, radix: 2))

简单加密 #

swift
let message: UInt8 = 0b01001000
let key: UInt8 = 0b10101010

let encrypted = message ^ key
print(String(encrypted, radix: 2))

let decrypted = encrypted ^ key
print(String(decrypted, radix: 2))

五、按位取反(~) #

5.1 基本用法 #

swift
let a: UInt8 = 0b00001111
let result = ~a

print(String(a, radix: 2).padLeft(toLength: 8, withPad: "0"))
print(String(result, radix: 2).padLeft(toLength: 8, withPad: "0"))

5.2 实际应用 #

清除特定位 #

swift
var value: UInt8 = 0b11111111
let mask: UInt8 = 0b00000100

value = value & ~mask
print(String(value, radix: 2))

六、移位运算 #

6.1 左移(<<) #

swift
let a: UInt8 = 0b00000001

let shifted1 = a << 1
let shifted2 = a << 2
let shifted3 = a << 3

print(String(shifted1, radix: 2))
print(String(shifted2, radix: 2))
print(String(shifted3, radix: 2))

6.2 右移(>>) #

swift
let a: UInt8 = 0b10000000

let shifted1 = a >> 1
let shifted2 = a >> 2
let shifted3 = a >> 3

print(String(shifted1, radix: 2))
print(String(shifted2, radix: 2))
print(String(shifted3, radix: 2))

6.3 有符号数移位 #

swift
let positive: Int8 = 8
let negative: Int8 = -8

print(String(positive >> 1, radix: 2))
print(String(negative >> 1, radix: 2))

6.4 实际应用 #

快速乘除 #

swift
let value = 5

let doubled = value << 1
let quadrupled = value << 2
let halved = value >> 1

print(doubled)
print(quadrupled)
print(halved)

七、位运算应用 #

7.1 权限管理 #

swift
struct Permission: OptionSet {
    let rawValue: Int
    
    static let read = Permission(rawValue: 1 << 0)
    static let write = Permission(rawValue: 1 << 1)
    static let execute = Permission(rawValue: 1 << 2)
    static let delete = Permission(rawValue: 1 << 3)
    
    static let all: Permission = [.read, .write, .execute, .delete]
}

var userPermission: Permission = [.read, .write]

print(userPermission.contains(.read))
print(userPermission.contains(.execute))

userPermission.insert(.execute)
print(userPermission.contains(.execute))

userPermission.remove(.write)
print(userPermission.contains(.write))

7.2 颜色处理 #

swift
func getRed(_ color: UInt32) -> UInt8 {
    return UInt8((color >> 16) & 0xFF)
}

func getGreen(_ color: UInt32) -> UInt8 {
    return UInt8((color >> 8) & 0xFF)
}

func getBlue(_ color: UInt32) -> UInt8 {
    return UInt8(color & 0xFF)
}

func makeColor(red: UInt8, green: UInt8, blue: UInt8) -> UInt32 {
    return (UInt32(red) << 16) | (UInt32(green) << 8) | UInt32(blue)
}

let color: UInt32 = 0xFF8000
print("R: \(getRed(color)), G: \(getGreen(color)), B: \(getBlue(color))")

let newColor = makeColor(red: 255, green: 128, blue: 0)
print(String(newColor, radix: 16))

7.3 位标志 #

swift
struct FileAttributes: OptionSet {
    let rawValue: Int
    
    static let readOnly = FileAttributes(rawValue: 1 << 0)
    static let hidden = FileAttributes(rawValue: 1 << 1)
    static let system = FileAttributes(rawValue: 1 << 2)
    static let archive = FileAttributes(rawValue: 1 << 3)
}

var attributes: FileAttributes = [.readOnly, .hidden]
print(attributes.contains(.readOnly))
print(attributes.contains(.archive))

attributes.insert(.archive)
attributes.remove(.hidden)

7.4 奇偶判断 #

swift
func isEven(_ number: Int) -> Bool {
    return (number & 1) == 0
}

func isOdd(_ number: Int) -> Bool {
    return (number & 1) == 1
}

print(isEven(4))
print(isOdd(7))

7.5 交换两个数 #

swift
var a = 5
var b = 10

a = a ^ b
b = a ^ b
a = a ^ b

print("a: \(a), b: \(b)")

八、扩展String #

swift
extension String {
    func padLeft(toLength length: Int, withPad pad: String) -> String {
        let padLength = length - self.count
        if padLength <= 0 { return self }
        return String(repeating: pad, count: padLength) + self
    }
}

let binary = String(42, radix: 2)
print(binary.padLeft(toLength: 8, withPad: "0"))

九、总结 #

本章学习了Swift的位运算符:

  • 按位与(&):掩码、检查位
  • 按位或(|):设置位
  • 按位异或(^):切换位、加密
  • 按位取反(~):反转位
  • 移位运算:快速乘除、位操作

最佳实践:

  • 使用OptionSet管理标志位
  • 注意有符号数的移位
  • 使用位运算优化性能
  • 添加注释说明位操作意图

下一章,我们将学习运算符优先级!

最后更新:2026-03-26