Converting integer to character Arduino

Converting an integer to character is an easy process. It involves first changing the integer into a string and then converting the string into a character array. The reason i am posting this short post is because just recently i realized that many people do not know how to convert an integer to a character, me included (well, but now i know).

I going to start with the easier option - Converting a character to integer, then move on to our point of interest.

Step 1: Character to integer

To convert a character to an integer you use this short statement:

int a;

char b;

a=b-'0';

That's it!

Step 2: Integer to Character

This is more intricate than the last one. However, it is not as difficult as some (including me before I learnt how to do it) might think.

Here is the code:

int a=1;

char b[2];

String str;

str=String(a);

str.toCharArray(b,2);

By running this code, you will be able to convert an integer, into a character. However, as you will notice, the code above can only do conversions of numbers between -9 to 99 (thanks to a buddy who noted that on the comments). To be able to convert larger integers, change the array size of the character. Therefore, instead of:

char b[2];

you can use

char b[5];

to accomodate a n integer that has 5 digits. You can use any other array size depending on the size ofthe integer you want to convert.

To learn more about how to convert one data type into another and get the code snipets, please visit this page:

http://www.arduino-hacks.com/converting-integer-to-character-vice-versa/

 
 

Tag cloud

make build easy simple arduino making homemade solar laser printed portable cheap mini building custom cardboard wooden create super lego turn paracord chocolate your paper light intel