How to Convert Binary Numbers to Decimal (for upto 31 binary digits)

The logic behind converting a binary number to decimal is very simple. Today we will learn how to convert a binary number of upto 31 digits to decimal form.Let us see how to do this.
  • Digits of a number in the binary number system holds a value of 2*(n-1), 2*(n-2)...4.2.1, where n is the total number of digits. We are going to use this property to convert them into decimal numbers.
  • First, we need to create an input file to store the value of a large binary number. We make one vertical column for the input.
  • We create a one-dimensional array bin(i) to save the input and we can also display it at the time of execution. We set a counter for the number of digits read.
  • We assign each digit a value based on its place value
  • If by mistake, a digit has been assigned a value other than 0 and 1, we consider it as 1 and calculate the values.(See the program)
  • Finally, we sum up all the values generated to get the corresponding decimal number.
 Let's illustrate this with an example.
Logic used in the Program to Convert a Binary Number to Decimal

Now for the Fortran program,

!To convert a number from binary to decimalprogram bin_to_dec
    implicit none
    integer dec,count,i,bin(100)
 
    !To read a large binary number from file
    write (*,*) "Reading the binary value in 0s and 1s."
    write (*,*) "Make sure the input file has one digit per row."
   
    write (*,*) "The binary input is given below"
    write (*,*)
    open (1,file='binary.dat')
   
    count=0
    do i=1,100
        read (1,*,end=10) bin(i)
         if (i==1.or.i==21.or.i==31) then
        write (*,*) i,"st digit=", bin(i)!You can simply write 'digit number, i' instead of 'i'th digit. Makes things easier
        else if (i==2.or.i==22) then
        write (*,*) i,"nd digit=", bin(i)
        else if (i==3.or.i==23) then
        write (*,*) i,"rd digit=", bin(i)
        else
        write(*,*) i,"th digit=", bin(i)
        end if
        count=count+1
    end do


    !To convert all 1s to powers of 2.i.e.(digit*place value)
    10 do i=1,count
        if (bin(i)==0) then
        bin(i)=0
      else
      bin(i)=2**(count-i) !This ensures that any digit other than 1 and 0 is taken as 1
      end if
      end do
     
    !To sum up all the values
    dec=0
    do i=1,count
      dec=dec+bin(i)
      end do
   
      write (*,*)
      write (*,*) "The decimal value is ", dec
end program


Sample Output: The Largest Number that can be Displayed with the Program

1 comment: