Convert a two byte UInt8 array to a UInt16 in Swift

前端 未结 7 854
醉话见心
醉话见心 2020-11-30 03:00

With Swift I want to convert bytes from a uint8_t array to an integer.

\"C\" Example:

char bytes[2] = {0x01, 0x02};
NSData *data = [NSData dataWithBy         


        
7条回答
  •  情歌与酒
    2020-11-30 03:47

    How about

    let bytes:[UInt8] = [0x01, 0x02]
    let result = (UInt16(bytes[1]) << 8) + UInt16(bytes[0])
    

    With a loop, this easily generalizes to larger byte arrays, and it can be wrapped in a function for readability:

    let bytes:[UInt8] = [0x01, 0x02, 0x03, 0x04]
    
    func bytesToUInt(byteArray: [UInt8]) -> UInt {
      assert(byteArray.count <= 4)
      var result: UInt = 0
      for idx in 0..<(byteArray.count) {
        let shiftAmount = UInt((byteArray.count) - idx - 1) * 8
        result += UInt(byteArray[idx]) << shiftAmount
      }
      return result
    }
    
    println(bytesToUInt(bytes))    // result is 16909060
    

提交回复
热议问题