简体   繁体   中英

Conversion between binary and decimal number

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;
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM