在 C 或 C++ 中将二进制字符串转换为 int

标签 c string arduino int type-conversion

<分区>

我有一个用 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);

关于在 C 或 C++ 中将二进制字符串转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23616751/

相关文章:

C 全方位递归 WordSearch 求解器

C# - 用下划线和字母替换每个大写字母

python - 如何修改 Tkinter Text 小部件中的当前选择长度?

javascript - 在字符串中发送 "&"时遇到问题

android - 通过蓝牙将数据从 Arduino 发送到 Android 应用程序

c - 构建 C 程序时出错

c 中用户定义函数的冲突类型

error-handling - 蓝牙 HC-05 发送错误 1F 仅适用于 INQ 命令

c - 变量取一定值时的断点

c++ - 对简单的 Arduino 类进行故障排除