Conversion between binary and decimal number

拟墨画扇 提交于 2019-12-12 05:25:10

问题


I woud like to ask, what bin-'0' means in this piece of code which convert binary number to decimal. Thanks.

#include <stdio.h>
#include <stdlib.h>

int main(){
    char bin;
    int dec = 0;

    printf("Binary: \n");
    bin = getchar();

    while((bin != '\n')){
        if((bin != '0') && (bin != '1')){
            printf("Wrong!\n");
            return 0;
        }
        printf("%c",bin-'0');  // ?

        dec = dec*2+(bin-'0'); // ?
        bin = getchar();
    }

    printf("Decimal: %d\n", dec);

    return 0;
}

回答1:


bin - '0' converts the ASCII value of bin to its integer value. Given bin = '1', bin - '0' = 1




回答2:


This code is taking advantage of the fact that C++ chars are really just special ints. It's using getchar to take in a char that is either '0' or '1'. Now it needs to convert that into 0 or 1 (note that these are numbers, not chars). Given that the char '0' is one before '1', subtracting the value of char '0' from both will turn '0' into 0 and '1' into 1.

'0' - '0' = 0
'1' - '0' = 1


来源:https://stackoverflow.com/questions/13141542/conversion-between-binary-and-decimal-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!