C语言 如何扫描二进制数?



我正试图编写一小段代码,我可以扫描二进制数字,如00110011,并将其转换为整数作为数字。所以00110011等于51。我为它编写的代码是这样的

int main()
{
unsigned char byte;
int d;
scanf("%8s", &byte);
d = byte;
printf("%d,%c",d, byte);
return 0;
}

然而,给我一个48的输出。00000001也给我48,其他的也一样。我知道出了什么问题,它将0和1的字符串视为单个0,并且由于其字符是0x300d48,因此它输出48。我想知道是否有一种方法可以绕过这个问题,并将其扫描为二进制等效。

你的代码根本不起作用:

  • 你最多扫描8个字符加上一个空终止符,传递一个单字节变量的地址:这是未定义的行为。
  • d = byte不执行任何转换。字符'0'被读入byte,其ASCII值被存储到d,即48,作为程序的输出。

此外,scanf()中没有二进制编码的标准转换说明符。读取字符串是一种好方法,但应该传递一个更大的缓冲区,并使用循环将其转换为二进制:

#include <ctype.h>
#include <stdio.h>
int main() {
char buf[100];
/* read a sequence of at most 99 binary digits into buf */
if (scanf(" %99[01]", buf) == 1) {
unsigned int d = 0;
/* convert the binary digits one at a time into integer d */
for (int i = 0; buf[i]; i++) {
d = (d << 1) | (buf[i] - '0');
}
/* print value as a number */
printf("%s -> %dn", buf, d);
if (d == (unsigned char)d && isprint(d)) {
/* print value as a character if printable */
printf("%s -> %cn", buf, d);
}
}
return 0;
}

您还可以使用strtoul()将表示为二进制数字字符串的数字(或任何其他进制,最多36)转换为:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char buf[100];
/* read a sequence of at most 99 binary digits into buf */
if (scanf(" %99[01]", buf) == 1) {
unsigned long d = strtoul(buf, NULL, 2);
/* print value as a number */
printf("%s -> %lun", buf, d);
if (d == (unsigned char)d && isprint((unsigned char)d)) {
/* print value as a character if printable */
printf("%s -> %cn", buf, (unsigned char)d);
}
}
return 0;
}

请注意,strtoul()的行为将与第一个代码不同:strtoul()将在溢出时返回ULONG_MAX,而第一个示例只计算二进制字符串的低阶位。

我发现这个简单的函数应该很容易理解,它确实做到了。它是一种算法,它遵循你在现实生活中自然地用笔和纸来做它,但是你在编译它(gcc命令)时需要-lm来包含数学库,但是如果你只做一个for循环,你可以绕过pow()并包含问题。

#include <stdio.h>
#include <math.h>
int todecimal(long bno){
int dno = 0, i = 0, rem;
while (bno != 0) {
rem = bno % 10;
bno /= 10;
dno += rem * pow(2, i);
++i;
}
return dno;
}