Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
unsigned long var = val;
- var: variable name.
- val: the value you assign to that variable.
※ NOTES AND WARNINGS:
When unsigned variables are made to exceed their maximum capacity they "roll over" back to 0, and also the other way around:
Math with unsigned variables may produce unexpected results, even if your unsigned variable never rolls over.
The MCU applies the following rules:
The calculation is done in the scope of the destination variable. E.g. if the destination variable is signed, it will do signed math, even if both input variables are unsigned.
However with a calculation which requires an intermediate result, the scope of the intermediate result is unspecified by the code. In this case, the MCU will do unsigned math for the intermediate result, because both inputs are unsigned!
Why use unsigned variables at all?
- The rollover behaviour is desired, e.g. counters
- The signed variable is a bit too small, but you want to avoid the memory and speed loss of long/float.