The following Arduino (C++) code
void setup()
{
Serial.begin(115200);
byte b1 = 12;
byte b2 = 5;
const byte RING_BUFFER_SIZE = 64;
byte diff = b2 - b1;
byte diff2 = (byte)(b2 - b1) % RING_BUFFER_SIZE; //<---NOTE HOW THE (byte) CAST IS *REQUIRED* TO GET THE RIGHT RESULT!!!!
Serial.println(b1);
Serial.println(b2);
Serial.println(RING_BUFFER_SIZE);
Serial.println(diff);
Serial.println(diff2);
}
void loop()
{
}
produces the expected:
12
5
64
249
57 //<--correct answer
Whereas without the "(byte)" cast as shown here:
void setup()
{
Serial.begin(115200);
byte b1 = 12;
byte b2 = 5;
const byte RING_BUFFER_SIZE = 64;
byte diff = b2 - b1;
byte diff2 = (b2 - b1) % RING_BUFFER_SIZE; //<---(byte) cast removed
Serial.println(b1);
Serial.println(b2);
Serial.println(RING_BUFFER_SIZE);
Serial.println(diff);
Serial.println(diff2);
}
void loop()
{
}
it produces:
12
5
64
249
249 //<--wrong answer
Why the difference? Why does the modulo operator ONLY work with the explicit cast?
Note: "byte" = "uint8_t"