· Home · Programing · Small Integers ·

Small Integers

Using small integers when programming small microcontrollers like the Arduino can cause problems. Usually they are the best choice for variables. You need to be aware of their limitations. They might cause your programs to do unexpected things.

To make it easy to study, the examples on this page wii be using 8 bit integers. These come in two types, signed and unsigned. First we will look at Unsigned 8 bit integers. They can range between 0 and 255. Trying to use a value outside of that range can cause problems. Lets study addition first, here is a calculator.

Unsigned 8 Bit Addition
+ =

When you have an unsigned 8 bit integer that has the value 240 and then add 20 the result will 4. In the world outside of small integers you would expect the value 260. In this case there is an overflow of 5. Since 0 is a valid number, it works like this (0, 1, 2, 3, 4). It is also possible to have an underflow. To show that we have subtraction calculator.

Unsigned 8 Bit Subtraction
- =

An underflow an easy mistake to make. If you are trying to do a loop with a decreasing value that stops at 0. The start of that would look something like this for(byte i = 55; i<0 ; i--){}. This sort of looks ok, but 0 is the lowest value possible for a 'byte' data type. When the variable 'i' is 0 and you subtract 1 the result is not -1 but 255. This is an underflow. The loop will not end. Next is multiplication.

Unsigned 8 Bit Multiplication
* =

The rule for multiplication is the result needs twice the space of operands. The result multiplying of two 8 bit integers needs 16 bits. If the result is also 8 bit an overflow can result. That is the case when we multiply 65 by 4. The next case is division. It get strange in other ways.

Unsigned 8 Bit Division
/ =

The issue with division is strange looking results. If you divide 64 by 32 the result is 2. Then if you divide 64 by any number between 33 and 64 the result is always 1.

Additional Calculators for Signed 8 bit integers

Simular results can be shown for unsigned integers. Here are some calculators.

Signed 8 Bit Addition
+ =
Signed 8 Bit Subtraction
- =
Signed 8 Bit Multiplication
* =
Signed 8 Bit Division
/ =
· Home · Programing · Tinkering · Recreation · Thoughts · Site Map ·