Arduino is giving a weird output when using toInt()

226 views Asked by At

I'm trying to convert a string to an integer (which is actually a binary number) so that I can output the DEC value, but where the answer SHOULD be 63 (00111111), it's giving me -19961 as an output? It would be great if someone can help me correctly convert the string to an int :)

    // C++ code
//
const int button = 13;
int buttonPressed = 0;
int counter = 0;
int myInts[] = {0, 0, 1, 1, 1, 1, 1, 1};


void setup()
{
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop()
{
  buttonPressed = digitalRead(button); 
  if (buttonPressed == HIGH){
    counter = count();
    //rial.println(counter);
  }
  else{
    Serial.println("Button not pressed");
  }
  delay(1000);
}

int count()
{
  String myString = ""; //Empty string for constructing
  int add = 0;
  int i = 0;
  //Should add all the values from myInts[] into a string
  while(i < 8){
    myString = String(myString + myInts[i]);
    Serial.println(add);
    delay(1000);
    add++;
    i++;
  }
  Serial.println(myString);
  int myNumber = myString.toInt(); //Convert the string to int
  Serial.println(myNumber, DEC); //Should print 63 in this case
  return add;
}
1

There are 1 answers

1
nanofarad On BEST ANSWER

Your code currently does the following:

  • Concatenates all your integers together to make a string "00111111"
  • Attempts to convert it (as a string holding a base 10 integer) to the integer 111,111 (one hundred eleven thousand, one hundred eleven)
  • Hits integer overflow. The range of an Arduino int is -32768 to 32767 (65536 possible values), so the number you really have is 111111 - 2*65536 = -19961.

I don't believe that there's an overload of Arduino's ToInt that converts a binary string to an integer. Depending on the C++ support in Arduino, you may be able to use std::stoi as described here.

Instead, you may choose to do the conversion yourself - you can keep track of a number sum, and at each loop iteration, double it and then add the next bit:

  int sum = 0;
  for(int i = 0; i < 8; i++) {
    sum *= 2;
    sum += myInts[i];
    // print and delay if you want
  }

Over the eight iterations, sum ought to have values 0, 0, 1, 3, 7, 15, 31, and finally 63