-1

I was given this program to convert a inputted decimal number to a string which is binary number. Now this is a correct program and does work. I have a doubt in while loop the expression saying ch = (rem + 48); I believe value of remainder rem is ultimately going to be inherited by ch then why adding 0 ie. 48 in ascii terms is making difference. what is making addition of 48 convert rem to character form. If I just write ch = rem;, ch is not considered as character and adding 48 makes it charcter. But Why???

void main()
{
    char x[15],tmp,ch;
    int i=0,j=0,dno,rem;
    printf("\nEnter decimal number:");
    scanf("%d",&dno);
    while(dno>0)
    {
        rem = dno % 2;
        ch = (rem+48);
        x[j++] = ch;
        dno/=2;
    }
    x[j--]='\0';
    while(i<j)
    {
        tmp = x[j];
        x[j--] = x[i];
        x[i++] = tmp;
    }
    puts(x);
    return;
}
  • It is better practice (and much clearer) to use the "character literal" representation of `'0'` rather than the 'magic number' `48`! This may help (although the conversion is the other way round): https://stackoverflow.com/q/628761/10871073 – Adrian Mole Apr 10 '20 at 16:02
  • thanks brother that question link helped me a lot. thanks for help....... – Sulaiman Mutawalli Apr 10 '20 at 16:49

2 Answers2

0

ch is a number that represents an ascii character value

48 correspond to the character "0"

49 correspond to the character "1"

the sum of rem (0 or 1) to 48 leads to 48 or 49, respectively the characters "0" and "1"

Paolo
  • 15,233
  • 27
  • 70
  • 91
0

In C to convert a character digit to its equivalent integer value, we can use this relationship:

x = character - '0'

Similarly to convert a digit to its equivalent character digit, we use the relationship:

ch = digit + '0'

That's why adding 48 to your rem makes it a character.

Shubham
  • 1,153
  • 8
  • 20