0

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;
}
Useless
  • 64,155
  • 6
  • 88
  • 132
user1751550
  • 85
  • 2
  • 7

2 Answers2

4

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

tomahh
  • 13,441
  • 3
  • 49
  • 70
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
Cannoliopsida
  • 3,044
  • 5
  • 36
  • 61