Swift - 将Data数据转换为[UInt8](bytes字节数组)

时间:2024-04-30 14:10:06

有时上传或者发送图片、文字时,需要将数据转换为 bytes 字节数组。下面介绍两种将 Data 转换为 [UInt8] 的方法。

假设我们有如下 Data 数据要转换:
1
let data = "航歌".data(using: .utf8)!

方法一:使用 [UInt8] 新的构造函数

1
2
let bytes = [UInt8](data)
print(bytes)
Swift - 将Data数据转换为[UInt8](bytes字节数组)

方法二:通过 Pointer 指针获取

1
2
3
4
let bytes = data.withUnsafeBytes {
    [UInt8](UnsafeBufferPointer(start: $0, count: data.count))
}
print(bytes)