如何从 Swift 中的大端表示计算 Int 值?

How to calculate Int value from Big-endian representation in Swift?

我正在努力通过 BLE 传输一个 UInt16 值。根据我的阅读,为此目的,我需要将 UInt16 转换为 UInt8,这将被转换为类型 Data。我一直指的是 。例如,我使用了以下代码:

extension Numeric {
    var data: Data {
        var source = self
        return Data(bytes: &source, count: MemoryLayout<Self>.size)
    }
}
extension Data {
    var array: [UInt8] { return Array(self) }
}

let arr = [16, 32, 80, 160, 288, 400, 800, 1600, 3200]

for x in arr {
    let lenghtByte = UInt16(x)
    let bytePtr = lenghtByte.bigEndian.data.array
    print(lenghtByte, ":", bytePtr)
}

我不太明白的是,当我将 UInt16 转换为大端数组时,这些值如何加起来等于相应的实际值。希望这是有道理的。上面代码片段的输出是,

16 : [0, 16]
32 : [0, 32]
80 : [0, 80]
160 : [0, 160]
288 : [1, 32]
400 : [1, 144]
800 : [3, 32]
1600 : [6, 64]
3200 : [12, 128]

我想知道的是如何使用大端数组中的UInt8值来计算160之后的每个值? (即 [12,128] 如何同样等于 3200)。

提前谢谢你:)

data 属性 所做的是查看数字的二进制表示,将其分割成字节,然后将其放入 Data 缓冲区。例如,对于 big endian 中的 1600,二进制表示如下所示:

0000011001000000

请注意整数中有两个字节 - 00000110(十进制为“6”)和 01000000(十进制为“64”)。这就是 [6, 64] 的来源。

要从 [6, 64] 取回 1600,您只需要知道“6”实际上并不代表 6,就像 52 中的“5”不代表 5 一样,但是5 * 10。这里的“6”代表6 * 256,或者6 << 8(6向左移动8次)。总的来说,要取回号码,您需要

a << 8 + b

其中 a 是第一个数组元素,b 是第二个。

一般n个字节的数,可以这样计算:

// this code is just to show you how the array and the number relates mathematically
// if you want to convert the array to the number in code, see
// 
var total = 0
for (i, elem) in byteArray.enumerated() {
    total += Int(elem) << (8 * (byteArray.count - i - 1))
}