Hello,
It may sound like a very trivial question (well I'm a noob after all) but I've been searching everywhere all evening and my head hurts : How do you add bytes ? I want to calculate the sum of 8 bytes:
I tried:
Let data : [UInt8] = [0xFF,0xF0,0x0F,0x11,0xFF,0xFF,0xF0,0x0F]
let total = data.reduce(0, +)
let numberSum = data.reduce(0, { x, y in x + y})
var sum : UInt8 = 0
for i in 0...data.count-1 {
sum += data[i]
}reduce() does not seem to work with an array of UInt8 but it works with arrays of Int
The loop does not work either, I cannot find the right format for sum and I cannot manage the overflow when I +=
The final goal of all this is to calculate a simple checksum. I came across some very complex methods and I am sure there is a simplier way. The code below shows how I did it in C++ (Arduino):
byte data[]={0xFF,0xF0,0x0F,0x11,0xFF,0xFF,0xF0,0x0F};
byte sum = 0;
for ( int i=0; i<sizeof(data); i++) {
sum += data[i];
}
byte checksum = lowByte(sum);
// sum = 1292 (0x50C) checksum = CAny idea ?
Thanks