Using atoi() for bytes and booleans?

1. atoi() stands for ASCII To (decimal) Integral (whole number and no fractional).

2. Meaning of atoi()
If there is a char-type array (string) where the characters are numerals (range: 0 - 9) and are coded in their ASCII values (Fig-1 under Step-4), then the function atoi() will convert the array into "decimal integral" value. The result will be saved in an int-type variable. (An int-type variable can hold value of this range: -32768 to 32767 (0x8000 to 0x7FFF.)

3. Example:
(1) Given the following array containing ASCII values for the digits of this decimal number: 1234.

char myNum[] = "1234";    //last element is an invisible null-charcater (0 = '\0')
==> char myNum[] = {'1', '2', '3', '4', '\0'};   //this representation requires null-charcater 
==> char myNum[] ={0x31, 0x32, 0x33, 0x34, 0x00};  //actual representation in memory

int x = atoi(myNum);    //x is an int-type (16-bit) variable and can hold: -32768 to 32767
Serial.print(x, DEC); //Serail Monitor shows: 1234

4. ASCII Table


Figure-1:

5. Example Sketch

char myNum[20] = "";

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  while (Serial.available() > 0)
  {
    byte m = Serial.readBytesUntil('\n', myNum, 20);
    int x = atoi(myNum);
    Serial.println(x, DEC);   //shows decimal value of charcaters coming from Serial Monitor
  }
}
1 Like