-
Notifications
You must be signed in to change notification settings - Fork 0
How big is an "int"?
Up until now, we've been just using the base int
type...a signed integer. C provides keywords to indicate whether an int is signed or unsigned...and they are intuitively named signed
and unsigned
. Those declarations look like this:
signed int my_signed_number;
unsigned int my_unsigned_number;
Let's look a little closer at how the machine actually stores these variables in memory.
The atomic unit of our computer is the bit...and a bit can be a 1
or a 0
. The machine groups 8 of these bits together into a byte...meaning that there are 2^8 or 256 possible values for a byte:
- unsigned bytes can have values from 0 to 255
- signed bytes can have values from -128 to 127 (including 0)
We'll talk later about how those bits get interpreted...but if you are curious, you can read here (link to come later).
One cool thing that c gives us is "sizeof"...it returns, in bytes, how big a given "thing" is. For example, how big is our "int?" We can run the following code to find out:
void setup()
{
int test_int;
int int_size;
int_size = sizeof(test_int);
Serial.print("An int is ");
Serial.print(int_size);
Serial.println("Bytes");
}
Note that this size is platform dependent...meaning it can be different depending on which hardware and compiler you are running. Because of this, if we want more portable programs, we want to be able to exactly specify how big the variable is upon declaration, which leads to...
Arduino (and many other enviornments) declare some additional types for you to use that are specific as to the size and sign of a given number. They are:
-
int8_t
: Signed, 8 bit number -
uint8_t
: Unsigned 8 bit number -
int16_t
: Signed 16 bit number -
uint16_t
: Unsigned 16 bit number -
int32_t
: Signed 32 bit number -
uint32_t
: Unsigned 32 bit number
So lets say we're working with uint8_t
. What do you think will happen with this code?
uint8_t my_number = 255;
my_number++;
Serial.println(my_number);
Spoiler alert: it will print 0. That's because the bits "roll over"...and can often introduce unexpected results in your program. Bottom line: when you are defining a variable, think about those roll-over cases.
You also get roll-over in the other direction:
uint8_t my_number = 0;
my_number--;
Serial.println(my_number);
For this case, my_number becomes 255...it rolls-over to the top of the range.
Signed numbers also roll-over:
int8_t number1 = 127;
int8_t number2 = -128;
number1++;
number2--;
Serial.println(number1); // prints -128
Serial.println(number2); // prints 127