简体   繁体   中英

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

I have a

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

How would I create a new var newArray:[UInt16] from that?

try something like:

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 performs a function on each element of an array and returns a new array

UInt8 UInt8 combined bytepattern to UInt16

If your intention is, as hinted by MartinR in the comments to your question, to transform pairs of UInt8 (eg 8+8 bits) to a single UInt16 (16 bits), one possible solution is as follows:

/* 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:

/* 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
}

(Edit addition)

For a less bloated alternative, you could use NSData or UnsafePointer as described in the following Q&A:

(this Q&A is possibly a duplicate to this linked one)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM