我有一个填充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
答案 0 :(得分:1)
你根本不需要一串比特。就这样做:
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);
答案 1 :(得分:1)
你可以使用strtol()函数:
#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;
}