0

I wanted to post this on the Arduino forum but couldn't find any "new post" button...
Anyway, I wrote this function to convert a binary string into an int/long.
However, it doesn't always work with big numbers.

The following code is supposed to return "888888" but returns "888.887"

void setup() {
  Serial.begin(9600);
  String data = "11011001000000111000"; //888888
  Serial.print(binStringToInt(data));
}

unsigned long binStringToInt(String bin) {
  unsigned long total = 0;
  int binIndex = 0;
  for (int i = bin.length() - 1; i > - 1; i--) {
    total += round(pow(2, binIndex)) * (bin.charAt(i) - '0');
    binIndex++;
  }
  return total;
}
3
  • 1
    pow usually returns a floating type. Have you tried another method, for example bitwise shift? Commented Feb 5, 2021 at 8:56
  • 1
    don't use pow(2, binIndex). Use 1 << binIndex instead Commented Feb 5, 2021 at 9:18
  • 1
    Common misunderstanding: the StackExchange sites are not classical forums. They are Q&A sites. You post a "new question", but you need to have an account. Commented Feb 5, 2021 at 11:56

2 Answers 2

1

You can use a simpler function to achieve that:

long binary_to_int(char *binary_string){
    long total = 0;
    while (*binary_string)
    {
     total *= 2;
     if (*binary_string++ == '1') total += 1;
    }
    
    return total;
}

void setup(){
    Serial.begin(9600);
    String data = "11011001000000111000";
    Serial.print(binary_to_int(data.c_str())); // prints 888888
}

I used.c_str() to get a char * to Arduino String.

Sign up to request clarification or add additional context in comments.

Comments

1
  1. When programming Arduino rather forget about String and vectors, use C strings and C arrays as it is very resources limited.
  2. Never use floats and float functions when dealing with integers.
unsigned long long convert(const char *str)
{
    unsigned long long result = 0;

    while(*str)
    {
        result <<= 1;
        result += *str++ == '1' ? 1 : 0;
    }
    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.