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
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