Home > Back-end >  Binary representation of a number, why so
Binary representation of a number, why so

Time:05-26

int DecimalToBinary (int number){
    int binary = 0, remainder = 0, i = 1;
 
    while (number != 0){
         remainder = number % 2;
         number /= 2;
         binary  = remainder * i;
         i *= 10;
      }
    
    return binary;
 
}

There is a function that represents numbers from decimal to binary. With the first two lines of the while loop everything seems clear, but then, I don't understand why we need binary = remainder * i, and why i *= 10.

Please explain why this is the case.

CodePudding user response:

Although comments have already explained the answer. Consider the following number i.e. abcd. This number can also be represented as a*1000 b*100 c*10 d. This is the only purpose of line binary = remainder * i; and after every iteration we are multiplying i by 10 to increase the multiple. Hope it answered your query.

  •  Tags:  
  • c
  • Related