Skip to main content

Binary to decimal in FORTRAN

Short answer

Extract digits with MOD and integer division; accumulate decimal = Σ(digit × 2^position). Verify each digit is 0 or 1. For input 1011, output 11.

Write the program to convert a binary number to a decimal number using Fortran programming language.

Method. The binary number is read as an integer made of digits 0 and 1 (e.g. 1011). Repeatedly take the last digit with MOD(N,10), multiply by the power of 2 for its position, add it to the decimal value, and remove the digit with N/10 (integer division). A digit other than 0 or 1 is rejected.

      PROGRAM BIN2DEC
      INTEGER N, REM, DEC, P
      PRINT *, 'ENTER A BINARY NUMBER'
      READ *, N
      DEC = 0
      P = 0
   10 IF (N .GT. 0) THEN
         REM = MOD(N, 10)
         IF (REM .GT. 1) THEN
            PRINT *, 'NOT A BINARY NUMBER'
            STOP
         END IF
         DEC = DEC + REM * 2**P
         P = P + 1
         N = N / 10
         GO TO 10
      END IF
      PRINT *, 'DECIMAL VALUE = ', DEC
      STOP
      END

Sample: N = 1011 gives 1·8 + 0·4 + 1·2 + 1·1 = 11. N = 11010 gives 16 + 8 + 2 = 26.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 11 questions →