Convert a two byte UInt8 array to a UInt16 in Swift

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

    If the bytes are in an NSData object you may do (assume data:NSData):

    var number: UInt16 = 0
    data.getBytes(&number, length: sizeof(UInt16))
    

    The getBytes method writes up to two bytes in the memory location of number (similar to C's memcpy. This won't crash your app if data hasn't enough bytes.

    (edit: no need to use range if starting from beginning of buffer)

    0 讨论(0)
提交回复
热议问题