MySQL for the Internet of Things

(Steven Felgate) #1
Chapter 4 ■ Data transformation

integer and an unsigned integer may be the same size^3 (2 bytes), but the range of values is different because
an integer allows for sign-limiting values (+/-) to the range -32768 to 32767 while an unsigned integer stores
values in the range 0 to 65535.
You also need to consider precision for the data. Floating-point numbers are real numbers with a
number of decimals. Most platforms state quite clearly that floating-point data types are estimated and not
exact—again, because of the decimal portion. Thus, you must consider this when converting data types.
For example, if you change a floating-point number to an integer, you may have rounding issues. Of course,
changing an integer to a float may also introduce rounding issues. Similarly, changing a type from a larger
storage (number of bytes) to a smaller storage (fewer bytes), you run the risk of overflowing the destination
memory and generating an invalid value.
Another consideration is performing arithmetic. That is, the resulting value or intermediate values must
“fit” in the range of values for the data type. For example, if you add two unsigned integers and assign the
result to another unsigned integer, you must ensure the value is in the range 0 to 65535. Otherwise, the value
may overflow and cause a number of issues, most notably an incorrect value.


■Note some programming languages have strict type checking and can detect or warn when overflows are


possible, but this is no substitute for careful programming (using the correct data type).


You may be wondering what overflow is. Observe the following short Arduino sketch. Here I have two
variables, a long and an unsigned integer starting with a value of 65535. Watch what happens.


void setup() {
unsigned int uint_val = 65535;
long long_val = 65535;
Serial.begin(9600);
while (!Serial); // Wait until Serial is ready - Leonardo
Serial.print("1> ");
Serial.print(uint_val);
Serial.print(" ");
Serial.println(long_val);
Serial.print("2> ");
uint_val++;
long_val++;
Serial.print(uint_val);
Serial.print(" ");
Serial.println(long_val);
Serial.print("3> ");
uint_val++;
long_val++;
Serial.print(uint_val);
Serial.print(" ");
Serial.println(long_val);
}


void loop() {
}


(^3) I say may be the same size because variable size is dependent on the processor and platform. It is best to check the
documentation for your platform before considering memory allocations for data types.

Free download pdf