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