Convert a two byte UInt8 array to a UInt16 in Swift

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

    In Swift 5 or later you can convert the bytes [UInt8] to UInt16 value using withUnsafeBytes { $0.load(as: UInt16.self) }

    let bytes: [UInt8] = [1, 2]
    

    loading as UInt16

    let uint16 = bytes.withUnsafeBytes { $0.load(as: UInt16.self) } 
    

    To get rid of the verbosity we can create a generic method extending ContiguousBytes:

    extension ContiguousBytes {
        func object() -> T { withUnsafeBytes { $0.load(as: T.self) } }
    }
    

    Usage:

    let bytes: [UInt8] = [1, 2]
    let uint16: UInt16 = bytes.object()  // 513
    

提交回复
热议问题