C function to convert decimal to binary

This function is slightly tricky as the binary has to be either a very large number or should be a string. Let us consider the latter option. Convert  a number to binary and store it in a string.

void dectobin(int n,char  str[])//1
 {                              //2
     int i=0;                   //3
      while(n>0)             //4
      {                         //5
          int rem = n%2;        //6
          str[i++]=rem + 48;    //7
          n/=2;                 //8
      }
      str[i]='\0';             //10
      reverse(str);
  }
void reverse(char str[])
{
    int len;
    int i,j;
    len = strlen(str);
    for(i = 0,j=len-1;i<j;i++,j--)
         {
            ch= str[i];
            str[i]=str[j];
            str[j]= ch;
         }
}
   

Let us try to understand the function. Line 1 tells us that the function takes the decimal number  to be converted as first parameter (n) and string where binary number must be placed as second parameter (str). Also note that size is not speciifed for str. The size is not needed as null character indicates end of the string and we will place the null character at the end.
We also have string reverse function here. Function just swaps the characters from both ends of a string. We have to take care that we continue the loop len/2 times.


When a function has an array parameter, the size of the array need not be mentioned because the array acts as a pointer

In line 3 we are defining i  for subscript of array and initializing it to 0. Initialization is mandatory. If you do not initialize i will have some large random value. Line 4 starts a loop which will repeat as long as n is greater that zero. In line 6, we are getting remainder when n is divided by 2 and storing it in rem. This will be stored in the array. Finally the array is  reversed
In line 10, we null terminate the string str which is also mandatory.

Every C string must be null terminated 


Now it is time to use this function. Let us write our main.

#include <stdio.h>
void dectobin(int,char []);
void reverse(char[]);
int main()
{
      int num;
      char str[33]="";//num can have maximum 32 bits
      printf("Let us convert some numbers to binary");
      do
      {
           printf("Enter a decimal number or 0 to end:");
           scanf("%d",&num);
           if(num==0)
           {
               break;
           }
           dectobin(num,str);
           printf("Binary equivalent of %d is %s\n",num,str);
     }while(num>0);
     return 0;
}

The program will read a number and print it in binary until user presses 0.
Observe how the declaration of the function is given. dectobin is a function which takes an int and char [] as parameters and returns nothing.

Do you really want to see how the program works. Let us introduce a printf in the funtion. In the function after line 7 add a these two lines as follows

      printf("n = %d  rem = %d and str = %s\n",n,rem,str)
    str[i]=0;


Here is how our output looks like

Now you have been told that C is more efficient when bitwise operators are used. Can we write the function using bitwise operators? Yes and here is it.

 void dectobin(int n,char str[])
 {
       int i=0;
       while(n>0)
      { 
         str[i++]=(n&1) + 48;
         n >>=1;
      }
      str[i]='\0';
      reverse(str); 
 }


What is happening here? We know that least significant bit of a number is 1 or 0 and when the number is anded with 1, if LSB is 1 the result is 1 otherwise the result is 0. This way we get LSB of our number and store it in the array. Next we shift the number to the right, so that next bit will be in 0th position and this process is continued till all bits are converted.


Comments

Popular Posts