您的代码根本不起作用:
- 您最多扫描 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 -> %d\n", buf, d);
if (d == (unsigned char)d && isprint(d)) {
/* print value as a character if printable */
printf("%s -> %c\n", 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 -> %lu\n", buf, d);
if (d == (unsigned char)d && isprint((unsigned char)d)) {
/* print value as a character if printable */
printf("%s -> %c\n", buf, (unsigned char)d);
}
}
return 0;
}
但是请注意, 的行为strtoul()将与第一个代码不同:strtoul()将ULONG_MAX在溢出时返回,而第一个示例仅计算二进制字符串的低位。