Question

I have got a String filled up with 0 and 1 and would like to get an Integer out of it: (platform in an Arduino UNO)

String bitString = ""; 
int Number;
int tmp;

bitString = "";
  for (i=1;i<=10;i++)
  {
    tmp= analogRead (A0);
    bitString +=  tmp % 2;
    delay(50);
  }
// now bitString contains for example "10100110" 
// Number = bitstring to int <-------------
// In the end I want that the variable Number contains the integer 166
Was it helpful?

Solution

You don't need a string of bits at all. Just do this:

  int n = 0;  // unsigned might be better here
  for (i = 0; i < 10; i++) {
    int bit = analogRead(A0) & 1;
    putchar('0' + bit);
    n = (n << 1) | bit;
    delay(50);
  }
  printf("\n%d\n", n);

OTHER TIPS

you can use strtol() function :

#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char * argv[])
{
char *a = "10100110";

int b = (int) strtol(a, NULL, 2);

printf("%d", b); //prints 166

return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top