This question already has answers here:
Closed 5 years ago.
Converting string of 1s and 0s into binary value
(5个答案)
我有一个0和1填充的字符串,希望从中得到一个整数:
(位于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

最佳答案

你根本不需要一串比特。就这样做:

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

09-25 20:43