unsigned long

Description

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

Syntax

unsigned long var = val;

Parameter Values

  • var: variable name.
  • val: the value you assign to that variable.

Example Code

unsigned long time; void setup() { Serial.begin(9600); } void loop() { Serial.print("Time: "); time = millis(); //prints time since program started Serial.println(time); // wait a second so as not to send massive amounts of data delay(1000); }

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

unsigned long x; x = 0; x = x - 1; // x now contains 4294967295 - rolls over in negative direction x = x + 1; // x now contains 0 - rolls over

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.

See Also

ARDUINO BUY RECOMMENDATION

Arduino UNO R3
Arduino Starter Kit
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.

※ OUR MESSAGES