Commit 320b57d
committed
Fixed comparisons with (wrong) unsigned-to-signed integer promotions
The following snippet demonstrates the problem:
uint32_t millis0 = 0x5FFF0;
uint32_t millis1 = 0x60010;
uint16_t t0 = millis0;
Serial.println((uint16_t)millis1-t0); // prints -65504 WRONG
Serial.println((uint16_t)(millis1-t0)); // prints 32 OK
the subtraction promotes each of the operands to signed integers so
we must make sure that the cast is made after the operation.
To further simplify this logic and avoid this kind of subtle traps
the operation has been moved from the condition into a variable of
the desired size:
uint16_t d = millis1 - t0;
Serial.println(d); // prints 32 as well
Fix #411 parent 8cd6fef commit 320b57d
1 file changed
+10
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
248 | 248 | | |
249 | 249 | | |
250 | 250 | | |
251 | | - | |
| 251 | + | |
252 | 252 | | |
253 | 253 | | |
254 | 254 | | |
| |||
288 | 288 | | |
289 | 289 | | |
290 | 290 | | |
291 | | - | |
| 291 | + | |
| 292 | + | |
292 | 293 | | |
293 | 294 | | |
294 | 295 | | |
| |||
310 | 311 | | |
311 | 312 | | |
312 | 313 | | |
313 | | - | |
| 314 | + | |
| 315 | + | |
314 | 316 | | |
315 | 317 | | |
316 | 318 | | |
| |||
543 | 545 | | |
544 | 546 | | |
545 | 547 | | |
| 548 | + | |
546 | 549 | | |
547 | 550 | | |
| 551 | + | |
548 | 552 | | |
549 | | - | |
| 553 | + | |
550 | 554 | | |
551 | 555 | | |
552 | 556 | | |
553 | 557 | | |
554 | 558 | | |
555 | 559 | | |
556 | 560 | | |
557 | | - | |
| 561 | + | |
| 562 | + | |
558 | 563 | | |
559 | 564 | | |
560 | 565 | | |
| |||
0 commit comments