Convert a two byte UInt8 array to a UInt16 in Swift

前端 未结 7 859
醉话见心
醉话见心 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:43

    Assuming little endian encoding.

    To convert to UInt16 from [UInt8], you can do something like

    var x: [UInt8] = [0x01, 0x02]
    var y: UInt16 = 0
    y += UInt16(x[1]) << 0o10
    y += UInt16(x[0]) << 0o00
    

    For conversion to UInt32, this pattern extends to

    var x: [UInt8] = [0x01, 0x02, 0x03, 0x04]
    var y: UInt32 = 0
    y += UInt32(x[3]) << 0o30
    y += UInt32(x[2]) << 0o20
    y += UInt32(x[1]) << 0o10
    y += UInt32(x[0]) << 0o00
    

    Octal representation of the shift amount gives a nice indication on how many full bytes are shifted (8 becomes 0o10, 16 becomes 0o20 etc).

    This can be reduced to the following for UInt16:

    var x: [UInt8] = [0x01, 0x02]
    let y: UInt16 = reverse(x).reduce(UInt16(0)) {
        $0 << 0o10 + UInt16($1)
    }
    

    and to the following for UInt32:

    var x: [UInt8] = [0x01, 0x02, 0x03, 0x04]
    let y: UInt32 = reverse(x).reduce(UInt32(0)) {
        $0 << 0o10 + UInt32($1)
    }
    

    The reduced version also works for UInt64, and also handles values where the byte encoding does not use all bytes, like [0x01, 0x02, 0x03]

提交回复
热议问题