在C中将二进制格式字符串转换为int

Yon*_*ing 10 c

如何将二进制字符串(如"010011101")转换为int,如何将int(如5)转换为C中的字符串"101"?

Poi*_*nty 22

strtol标准库函数采用一个"基地"参数,在这种情况下将是2.

int fromBinary(const char *s) {
  return (int) strtol(s, NULL, 2);
}
Run Code Online (Sandbox Code Playgroud)

(我在大约8年写的第一个C代码:-)


Win*_*der 12

如果它是一个家庭作业问题,他们可能希望你实现strtol,你会有一个像这样的循环:

char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
 total *= 2;
 if (*start++ == '1') total += 1;
}
Run Code Online (Sandbox Code Playgroud)

如果你想得到想象,你可以在循环中使用它们:

   total <<= 1;
   if (*start++ == '1') total^=1;
Run Code Online (Sandbox Code Playgroud)