Conversion between binary and decimal number

2019-09-09 14:28发布

问题:

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