Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CHAR and ICHAR functions

Status
Not open for further replies.

andrea213

Programmer
Mar 27, 2014
2
PT
Hello,

I am trying to convert a high number (e.g. 123456789) into a character and then reconvert that character into the first number in another file.
To do this, I am using CHAR and ICHAR functions.
Using:

[tt] WRITE(*,*) ICHAR(CHAR(123456789,4),4) [/tt]

I get the number 123456789

However, when I try to separate the steps

[tt]
CHARACTER*1 TMPC1
INTEGER*4 TMPI1
INTEGER*4 NUMBER

NUMBER = 123456789

TMPC1 = CHAR (NUMBER,4)
TMPI1 = ICHAR (TMPC1,4)

WRITE(*,*) TMPI1 [/tt]

The ICHAR function only allows a character input of length 1 !!
I get the number 21. At first this was a bit confusing. It became clear when I used this program to convert the numbers 0, 1, 2, 3, ..., 300
The conversion was flawless until number 254, and then reseted:

253 > 253
254 > 254
255 > 255
256 > 0
257 > 1

This is due to the limited number of ASCII characters, which is 255.
Any thoughts on how to convert a number larger than 255, and retrieve the same number?

Many thanks!
 
Which compiler are you using? I've never seen ICHAR(number, kind) before.
 
What are you actually trying to achieve. Are you trying to convert a number into character form and then retrieve it from character form and convert it back to a number?
 
I am using the gfortran compiler.

xwb (Programmer)
What are you actually trying to achieve. Are you trying to convert a number into character form and then retrieve it from character form and convert it back to a number?

That's exactly what I am trying to do here.
 

The right way is to use READ and WRITE instead of ICHAR and CHAR.

Indeed, ICHAR/CHAR manage only bytes (1 byte = 8 bits = integer from 0 to 255 = a single character)

Code:
program test
  integer :: i,j
  character(9) :: c
  i=123456789
  write(c,'(i0)') i ! initializing the string c
  print*,c
  read(c,*) j ! reading back the integer from the string
  print*,j
end program

Result :

123456789
123456789


François Jacq
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top