0

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
  • 13
  • 116
  • 190
  • toInt expects a base 10 number - '001111' should be converted to 1111 – pm100 Jul 14 '22 at 18:10
  • Not an Arduino expert, but I think `toInt()` might expect a decimal string, not a binary string. That is, "11" is eleven, not three. – BoP Jul 14 '22 at 18:11
  • The standard AVR library has `strtol()` which can do this. Might need to `#include ` first. Then `mynum = strtol(mystring.c_str(), NULL, 2);` to convert a base-2 string to a long integer. We need to use `c_str()` to get the C-string from the Arduino's String string. Good luck! – aMike Jul 15 '22 at 00:12

1 Answers1

0

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

nanofarad
  • 40,330
  • 4
  • 86
  • 117