How to Convert Decimal Numbers to Binary

In the previous program, we learned how to convert a binary number to decimal. Now, let us learn how to convert decimal to binary. Here is how it works.
  • We first need to read the decimal number, dec as usual. At this time we set the counter to zero.
  • We check if the number is divisible by 2. If the number is divisible  i.e. mod (dec,2)=0, then we set the binary value to 0, else we set it to 1. These values are stored in a one dimensional array.
  • We then divide the number by 2 and use the truncated result as the next dec value.We increase the count every time we divide the number. So this step, along with the previous one, is put in a do loop.
  • Finally, we exit the loop when we get dec=0 and flip the order of digits in the array. This gives us the binary form of the number.
Let us see an example.
Logic used in the Program to Convert a Decimal Number to Binary

Now, for the Fortran Program,

!To convert decimal numbers to binary
program dec_to_bin
    implicit none
    integer dec,count,i,bin(100),rep

    !To read the input
    10 write (*,*) "Give the number in decimal number system"
    read (*,*) dec
    write (*,*) "The decimal value is ,",dec

   
    count=0
       do i=1,100
     
         if (mod(dec,2)==0) then
               bin(i)=0
               else
             bin(i)=1
        end if
        dec=dec/2 !Notice the use of truncated result
        count=count+1
       
        if (dec==0) then
            exit
        end if
       
    end do
    write(*,*) "The binary value is given below"
    write (*,*)(bin(i),i=count,1,-1)
    write(*,*)
  
    !To read more values. Optional
    write (*,*) "Press 1 to add more values"
    read (*,*) rep
    if (rep==1) then
        goto 10
        else
        stop
    end if
    write (*,*)
   
end program dec_to_bin


Sample Output for Decimal to Binary Conversion
Note that 2^31-1=2147483647 is the largest number that can be produced. This upper limit is the same of binary to decimal conversion as well.

No comments:

Post a Comment