簡體   English   中英

如何在Swift中將[UInt8]轉換為[UInt16]?

[英]How would I convert a [UInt8] to [UInt16] in Swift?

我有一個

var byteArr:[UInt8] = [126, 34, 119, 55, 1, 159, 144, 24, 108, 226, 49, 178, 60, 119, 133, 97, 189, 49, 111, 208]

我將如何從中創建一個新的var newArray:[UInt16]

嘗試類似的東西:

var byteArr:[UInt8] = [126, 34, 119, 55, 1, 159, 144, 24, 108, 226, 49, 178, 60, 119, 133, 97, 189, 49, 111, 208]

var newArray:[UInt16] = byteArr.map { UInt16($0) }

map對數組的每個元素執行一個函數,然后返回一個新數組

UInt8 UInt8將字節UInt8 UInt8組合到UInt16

如MartinR在對問題的評論中所暗示的,如果您打算將成對的UInt8 (例如8 + 8位)轉換為單個UInt16 (16位),則一種可能的解決方案如下:

/* pair-wise (UInt8, UInt8) -> (bytePattern bytePattern) -> UInt16       */
/* for byteArr:s of non-even number of elements, return nil (no padding) */
func byteArrToUInt16(byteArr: [UInt8]) -> [UInt16]? {
    let numBytes = byteArr.count
    var byteArrSlice = byteArr[0..<numBytes]

    guard numBytes % 2 == 0 else { return nil }

    var arr = [UInt16](count: numBytes/2, repeatedValue: 0)
    for i in (0..<numBytes/2).reverse() {
        arr[i] = UInt16(byteArrSlice.removeLast()) +
                 UInt16(byteArrSlice.removeLast()) << 8
    }
    return arr
}

用法示例:

/* example usage */
var byteArr:[UInt8] = [
    255, 255,  // 0b 1111 1111 1111 1111 = 65535
    0, 255,    // 0b 0000 0000 1111 1111 = 255
    255, 0,    // 0b 1111 1111 0000 0000 = 65535 - 255 = 65280
    104, 76]   // 0b 0110 1000 0100 1100 = 26700

if let u16arr = byteArrToUInt16(byteArr) {
    print(u16arr) // [65535, 255, 65280, 26700], OK
}

(編輯添加)

對於較腫的替代方案,您可以按照以下問答中的描述使用NSDataUnsafePointer

(此問答可能是此鏈接的問答的重復)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM