Search code examples
fortrangfortran

How to write characters in reverse order ( from last to first ) from character variable into integer variable?


My IDE is: CodeBlocks 20.03 ( MinGW 9.3.0 )

My code is:

  function fun_conversion( n_numb_tmp, n_base_tmp ) result( data_tmp )

    integer, intent(in) :: n_numb_tmp
    integer, intent(in) :: n_base_tmp
    integer             ::   data_tmp
    integer             :: n_div, n_div_res
    character(1)        :: char_01
    character(4)        :: char_02
    
    n_div = 0

    n_div = n_numb_tmp / n_base_tmp

    write(char_01,'(i0)') ( n_div * n_base_tmp ) - n_numb_tmp
    
    char_02 = char_01

    do while ( n_div /= 0 )
        
      n_div_res = n_div

      n_div = n_div / n_base_tmp 

      write(char_01,'(i0)') n_div_res - ( n_div * n_baza_tmp )

      char_02 = trim(char_02) // char_01
               
    end do

   ! data_tmp = ?????

  end function fun_conversion

How to enter all integer remainders of division from the last remainder to the first in the variable data tmp? The algorithm is in pic attachment

data_tmp


Solution

  • If you just need to reverse a string of constant length you can do it as follows

    module foo_m
      implicit none
    contains
      integer function str2reverted_int(str) result(res)
        character(*), intent(in) :: str
    
        character(len(str)) :: rev_str
        integer             :: i, n
    
        n = len(str)
    
        rev_str(1:1) = str(n:n)
        do i = 2, n
          rev_str(i:i) = str(n+1-i:n+1-i)
        end do
    
        read (rev_str, *) res
      end function
    end module
    
    program main
      use foo_m
      implicit none
    
      print *, str2reverted_int('1234')     ! -> '4321'
      print *, str2reverted_int('12345')    ! -> '54321'
    end program