Tips and Tricks (Part 21)
Convert numerical values in strings of characters.
Converting numerical values into strings of characters is easy as far as Serial functions is concerned . However you may face one day or another the need for converting a numerical value for insertion within an existing string of characters (e.g. LCD, commands sent through SPI, etc.). Here is a collection of converting functions and their Serial equivalents. But firstly, we need to create a buffer which will contain the output from the conversion functions:
char *_vBuffer; void setup(void) { _vBuffer = (char*) malloc(16 * sizeof(char)); Serial.begin(115200); }
These few lines of code constitute the header and the setup section of the code. And here are the converting instructions:
/* Convert signed 32 bits integer */ ltoa(2863311530, _vBuffer, 10); /* Results in -1431655766 */ Serial.println(_vBuffer); /* Same as */ Serial.println(int32_t(2863311530)); /* Convert unsigned 32 bits integer */ ultoa(2863311530, _vBuffer, 10); /* Results in 2863311530 */ Serial.println(_vBuffer); /* Same as */ Serial.println(2863311530); /* Convert 32 bits integer to hex */ itoa(2863311530, _vBuffer, 16); /* Results in AAAAAAAA */ Serial.println(_vBuffer); /* Same as */ Serial.println(2863311530, HEX); /* Convert unsigned 16 bits integer */ utoa(43690, _vBuffer, 10); /* Results in 43690 */ Serial.println(_vBuffer); /* Same as */ Serial.println(43690); /* Convert signed 16 bits integer */ itoa(43690, _vBuffer, 10); /* Results in -21846 */ Serial.println(_vBuffer); /* Same as */ Serial.println(int16_t(43690)); /* Convert integer to hex */ itoa(43690, _vBuffer, 16); /* Results in AAAA */ Serial.println(_vBuffer); /* Same as */ Serial.println(43690, HEX); /* Convert float using 6 decimals */ dtostrf(M_PI, 8, 6, _vBuffer); Serial.println(_vBuffer); /* Same as */ Serial.println(M_PI, 6);
More details about the converting function here
HTH