문제

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
도움이 되었습니까?

해결책

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

다른 팁

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top