anyinteger_to_string Function

public impure function anyinteger_to_string(int) result(out)

NAME

anyinteger_to_string(3f) - [M_anything] convert integer of any kind to a string
(LICENSE:MIT)

SYNOPSIS

impure function anyinteger_to_string(intin) result(str)

 character(len=:),allocatable :: anyinteger_to_string
 class(*),intent(in)          :: intin

DESCRIPTION

Converts an integer value to a string representing the value.
This function allows arguments of different INTEGER types as input.

OPTIONS

VALUEIN  INTEGER input argument to be converted to a string.
         May be of KIND kind=int8, kind=int16, kind=int32, kind=int64.

RESULTS

         The value of VALUIN converted to a CHARACTER string.

EXAMPLE

Sample program

program demo_anyinteger_to_string
use, intrinsic :: iso_fortran_env, only : int8, int16, int32, int64
use M_anything, only : itoc=>anyinteger_to_string
implicit none
   write(*,*)itoc(huge(0_int8)),       '=> 127'
   write(*,*)itoc(huge(0_int16)),      '=> 32767'
   write(*,*)itoc(huge(0_int32)),      '=> 2147483647'
   write(*,*)itoc(huge(0_int64)),      '=> 9223372036854775807',huge(0_int64)
   write(*,*)itoc(-(huge(0_int64)-1)), '=> -9223372036854775806'
end program demo_anyinteger_to_string

Results:

127=> 127
32767=> 32767
2147483647=> 2147483647
9223372036854775807=> 9223372036854775807
-9223372036854775806=> -9223372036854775806

AUTHOR

John S. Urban

LICENSE

MIT

Arguments

Type IntentOptional Attributes Name
class(*), intent(in) :: int

Return Value character(len=:), allocatable


Source Code

impure function anyinteger_to_string(int) result(out)

! ident_8="@(#) M_anything anyinteger_to_string(3f) function that converts an integer value to a character string"

class(*),intent(in)          :: int
character(len=:),allocatable :: out
integer,parameter            :: maxlen=32         ! assumed more than enough characters for largest input value
integer                      :: i, k
integer(kind=int64)          :: intval
integer(kind=int64)          :: int_local
integer                      :: str(maxlen)
integer,parameter            :: dig0=  ichar('0')
integer,parameter            :: minus= ichar('-')

   int_local = anyscalar_to_int64(int)            ! convert input to largest integer type
   intval = abs(int_local)
   do i=1,maxlen                                  ! generate digits from smallest significant digit to largest
      str(i) = dig0 + mod(intval,10_int64)
      intval = intval / 10
      if(intval == 0 )exit
   enddo
   if (int_local < 0 ) then                       ! now make sure the sign is correct
      i=i+1
      str(i) = minus
   endif
   allocate(character(len=i) :: out)
   do k=i,1,-1                                    ! have all the digits in reverse order, now flip them and convert to a string
      out(i-k+1:i-k+1)=char(str(k))
   enddo
end function anyinteger_to_string