[英]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
轉換為大端數組時,這些值如何加起來等於相應的實際值。 希望這是有道理的。 上面代碼段的 output 是,
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]
我想知道的是如何使用 Big-endian 數組中的UInt8
值計算 160 之后的每個值? (即 [12,128] 如何等同於 3200,同樣)。
先感謝您:)
data
屬性的作用是查看數字的二進制表示,將其分割成字節,然后將其放入Data
緩沖區。 例如,對於 big endian 中的 1600,二進制表示如下所示:
0000011001000000
請注意,integer 中有兩個字節 - 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
// https://stackoverflow.com/a/38024025/5133585
var total = 0
for (i, elem) in byteArray.enumerated() {
total += Int(elem) << (8 * (byteArray.count - i - 1))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.