Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

Arduino C/C++ Convert binary string to decimal

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;
}
question from:https://stackoverflow.com/questions/66060239/arduino-c-c-convert-binary-string-to-decimal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...