Ama*_*nda 2 arrays byte type-conversion bit swift
我正在尝试解码一个protobuff编码的消息,所以我需要将protobuff消息中的第一个字节(密钥)转换成位,这样我就可以找到字段编号.如何将UInt8(字节)转换为位数组?
伪代码
private func findFieldNum(from byte: UInt8) -> Int {
//Byte is 0001 1010
var fieldNumBits = byte[1] ++ byte[2] ++ byte[3] ++ byte[4] //concatentates bits to get 0011
getFieldNum(from: fieldNumBits) //Converts 0011 to field number, 2^1 + 2^0 = 3
}
Run Code Online (Sandbox Code Playgroud)
我看到了这个问题,它将一个位数组转换为字节数组.
这是Bit从字节获取数组的基本函数:
func bits(fromByte byte: UInt8) -> [Bit] {
var byte = byte
var bits = [Bit](repeating: .zero, count: 8)
for i in 0..<8 {
let currentBit = byte & 0x01
if currentBit != 0 {
bits[i] = .one
}
byte >>= 1
}
return bits
}
Run Code Online (Sandbox Code Playgroud)
这Bit是我定义的自定义枚举类型,如下所示:
enum Bit: UInt8, CustomStringConvertible {
case zero, one
var description: String {
switch self {
case .one:
return "1"
case .zero:
return "0"
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用此设置,输出以下代码:
let byte: UInt8 = 0x1f
print(bits(fromByte: byte))
Run Code Online (Sandbox Code Playgroud)
将会:
[1, 1, 1, 1, 1, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4634 次 |
| 最近记录: |