0

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
3
  • @LaughDonor looks like this does not work on an Arduino Commented May 12, 2014 at 19:06
  • :/ I wasn't sure if all the libraries were available on that platform. Commented May 12, 2014 at 19:08
  • look at long strtol (const char String_Input[], char **End_Pointer, int Base); i.e. int num = strtol(bitString, NULL, 2); Commented May 12, 2014 at 19:15

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

looks like it does the job. how can I print out the binary string?
That depends. I'll edit the above to show one way.
1

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.