Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to convert from dec to bin, consist of 3 lines, need explanation

Tags:

c

I want one to explain the following function accurately.

void ToBin(int n){
  if (n>1)
     ToBin( n/2 );
  printf( "%d", n%2 );
}

For example:
If I'm entered 7, what's happen (the function behavior) to convert to binary 111.

Please I want step by step explanation to I understand.


Edit
The same function but prints the result more clearly.

void ToBin( int n ){
   printf("%d/2= %d -> %d\n", n, n/2 ,n%2);
   if (n>1)
      ToBin( n/2 );
}
like image 532
Lion King Avatar asked Dec 07 '22 06:12

Lion King


1 Answers

With 7 in particular:

First, n = 7, so n > 1. Thus, ToBin is called again on n / 2 = 3.

Now, n = 3, so n > 1. Thus, ToBin is called again on n / 2 = 1.

Now, n = 1, so n is not greater than 1. Thus, 1 % 2 = 1 is printed, and control jumps back to the previous frame.

Here, n = 3, and 3 % 2 = 1 is printed, with control jumping back a frame again.

Here, n = 7, and 7 % 2 = 1 is printed, and as the function is left and there are no more ToBin frames left, control is returned to the function that originally called ToBin.

In general, this function works as follows:

The binary expression of a number is equal to the binary expression of the floor of half that number, with the lowest bit of the original number appended.

Thus, the function repeatedly gets the binary expression of the floor of half the input until that value is a single bit. Then, that bit, being the most significant bit of the number, is printed, and subsequently, so is each bit in descending order of significance.

like image 171
qaphla Avatar answered Dec 15 '22 00:12

qaphla