2

我正在尝试编写一小段代码,我可以在其中扫描二进制数字,例如00110011,并将其转换为整数作为数字。51也是如此00110011。我为此编写的代码是这样的

int main()
{
    unsigned char byte;
    int d;

    scanf("%8s", &byte);

    d = byte;

    printf("%d,%c",d, byte);
    return 0;
}

然而,这给了我一个输出4800000001也给了我48,其他任何东西也是如此。我知道出了什么问题,它将 0 和 1 的字符串视为一个字符串,0并且由于其字符为0x30, 或0d48,因此它输出48. 我不知道是否有办法绕过这个并将其扫描为二进制等效项。

4

2 回答 2

2

您的代码根本不起作用:

  • 您最多扫描 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在溢出时返回,而第一个示例仅计算二进制字符串的低位。

于 2021-09-17T18:59:23.770 回答
0

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

#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;
}
于 2021-09-17T19:03:20.670 回答