Swift-将UInt8字节转换为位数组 [英] Swift - Convert UInt8 byte to array of bits

查看:411
本文介绍了Swift-将UInt8字节转换为位数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解码一个Probuff编码的消息,因此我需要将Probuff消息中的第一个字节(密钥)转换为位,以便找到字段号.如何将UInt8(字节)转换为位数组?

I'm trying to decode a protobuff encoded message, so I need to convert the first byte (the key) in the protobuff message into bits, so I can find the field number. How do I convert a UInt8 (the byte) into an array of bits?

伪代码

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
}

我看到了这个问题,它转换了一个数组位变成字节数组.

I saw this question, which converts an array of bits into array of bytes.

推荐答案

这是从字节中获取Bit数组的基本功能:

Here's a basic function to get a Bit array from a byte:

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
}

在这里,Bit是我定义的自定义枚举类型,如下所示:

Here, Bit is a custom enum type that I have defined as follows:

enum Bit: UInt8, CustomStringConvertible {
    case zero, one

    var description: String {
        switch self {
        case .one:
            return "1"
        case .zero:
            return "0"
        }
    }
}

使用此设置,将输出以下代码:

With this setup, the output of the following code:

let byte: UInt8 = 0x1f

print(bits(fromByte: byte))

将是:

[1, 1, 1, 1, 1, 0, 0, 0]

这篇关于Swift-将UInt8字节转换为位数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆