# Swift实用小册25: 高级运算符之位运算符的使用

·  阅读 2001

## 前言

`Apple`官网或者网上分享的教程类文章不同，我将以实际开发角度讲述`Swift`语言的一些概念和用法，方便大家更好地学习和掌握`Swift`语言。

## 按位取反运算符

``````var bits: UInt8 = 0b00001111
bits = ~bits
print("\(bits)")
``````

`UInt8``8`个比特位，可以存储`0～255`之间的数值。

## 按位与运算符

``````let firstBits: UInt8 = 0b00001111
let lastBits: UInt8  = 0b11110000
let resultBits = firstBits & lastBits
print("\(resultBits)")
``````

## 按位或运算符

``````let firstBits2: UInt8 = 0b00001111
let lastBits2: UInt8 = 0b11110000
let resultBits2 = firstBits2 | lastBits2
print("\(resultBits2)")
``````

## 按位亦或运算符

``````let firstBits3: UInt8 = 0b00001111
let lastBits3: UInt8 = 0b11110000
let resultBits3 = firstBits3 ^ lastBits3
print("\(resultBits3)")
``````

## 按位左移（右移）运算符

``````let bits2: UInt8 = 4 // 即二进制的 00000100
bits2 << 1          // 00001000
bits2 << 2          // 00010000
bits2 << 5          // 10000000
bits2 << 6          // 00000000
bits2 >> 2          // 00000001
``````

## 本章代码

``````import UIKit

var bits: UInt8 = 0b00001111
bits = ~bits
print("\(bits)”)

let firstBits: UInt8 = 0b00001111
let lastBits: UInt8  = 0b11110000
let resultBits = firstBits & lastBits
print("\(resultBits)”)

let firstBits2: UInt8 = 0b00001111
let lastBits2: UInt8 = 0b11110000
let resultBits2 = firstBits2 | lastBits2
print("\(resultBits2)”)

let firstBits3: UInt8 = 0b00001111
let lastBits3: UInt8 = 0b11110000
let resultBits3 = firstBits3 ^ lastBits3
print("\(resultBits3)”)

let bits2: UInt8 = 4
bits2 << 1
bits2 << 2
bits2 << 5
bits2 << 6
bits2 >> 2
``````

iOS

iOS