3

What is the best way to concatenate two integers to an integer in Fortran?

integer a = 999
integer b = 1111

integer c should be 9991111

Thanks, SM.

milancurcic
  • 6,202
  • 2
  • 34
  • 47
SkypeMeSM
  • 3,197
  • 8
  • 43
  • 61

3 Answers3

8

Here is an example code that does what you need. It writes integers into character strings, trims and concatenetes them, and then reads the result integer from concatenated character string:

integer :: a,b,c
character(len=99) :: char_a,char_b,char_c

a = 999
b = 1111

write(unit=char_a,fmt=*)a
write(unit=char_b,fmt=*)b

char_c = trim(adjustl(char_a))//trim(adjustl(char_b))

read(unit=char_c,fmt=*)c

print*,c

end

Edit: Note that this example is general for any integer lengths, assuming they fit into their respective kind (no integer overflow).

milancurcic
  • 6,202
  • 2
  • 34
  • 47
3

You can use the information of the order of the number:

integer :: a = 999
integer :: b = 1111

integer :: c

c = a * 10**(ceiling(log10(real(b)))) + b

write(*,*) c
steabert
  • 6,540
  • 2
  • 26
  • 32
0

Your best bet is to use internal files to convert your two integers to a character, and then convert this back to an integer.

There is no intrinsic procedure for converting a numeric value to a character/string representation. See this discusson on Fortran Wiki for more information (see the part headed "Note").

As an example, in your case you could use the following:

program test_conversion
  implicit none

  integer :: a=999
  integer :: b=1111
  integer :: c

  character(len=7) :: temp

  write(temp, '(i3.3, i4.4)') a, b ! You may need to change these format specifiers

  read(temp, *) c

  print*, c ! This prints 9991111

end program test_conversion

You will have to change the format string if you want different widths of the character representation of your integers.

Community
  • 1
  • 1
Chris
  • 44,602
  • 16
  • 137
  • 156
  • The line 'write(c, *) temp' does not do what you think. It will write temp into a I/O unit having a value of integer c, and not into c itself. Instead, you need to read c from temp. – milancurcic Feb 01 '12 at 16:54
  • That was an mistype on my part - copied and pasted from the line above. Thanks for pointing it out. – Chris Feb 01 '12 at 16:56
  • No problem. Just out of curiosity, I tried your code with ifort, pgf90 and gfortran. Strangely enough, ifort12 seems to write temp into integer c and print it, which is not expected/desired behavior. pgf90 and gfortran behave as expected, generating fort.gibberish files as output. – milancurcic Feb 01 '12 at 17:00
  • I assume you mean my previous, incorrect code? I just tried it with gfortran under cygwin and it also writes temp into an integer and prints it, which is rather strange. – Chris Feb 01 '12 at 17:11
  • 1
    Yes, I mean the previous code. I always enjoy discovering bugs in compilers though. – milancurcic Feb 01 '12 at 18:20