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)