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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to read unsigned integers in F90 programs?

Status
Not open for further replies.

rock31

Programmer
Jul 18, 2004
38
US
Hello,
I need to use a Fortran program to read a group of data stored as unsigned integers.
In F90, it sounds the rule to declare an integer only applies to signed integers.

I am thinking to read in unsigned data first as signed integers, then convert them to signed integers (if there exists a function such as “convert()” to the job).
For example, to read a given unsigned integer stored in file “data”, I may write a short code as below

implicit none
integer :: x
integer :: convert
open(1, filename='data')
read(1,*)x
x=convert(x)
print*, x
close(1)
end

Now, the questions are: 1. I am not sure if it is ok to read an unsigned integer in the way to read signed integer. 2. if the first step is OK, how to write a convert function.

Thanks a lot
 
now, I know the method I posted above is wrong. The unsigned integers and signed integers can not be distinguished internally by a compiler.

 
Hello,
Here, I reply my own post, and give a list of my research to the problem. Overall there are several methods.

1. For 1 byte integer, it can be dealt with ichar(), e.g.

implicit none
character*1 :: x:))
integer*4 :: i,data:))
allocate(x(len)) ! len is the length of data record.
allocate(data(len))
read(unit, *)x
do i=1,len
data(i) = ichar(x(i))
end do
end

2. Sometimes, the unsigned integers can be stored with signed integers with same size. Then convert the integer into the signed actual value, e.g. to read an unsigned integer with 4 bytes,

integer*4 :: x:))
read(1,*)x
where (x > 2**3-1) x=x-2**4+1
end

3. If you use F95, it will be very simple, because F95 supports unsigned integers, e.g.

unsigned u
unsigned(KIND=2) :: a
unsigned*8 :: b

If you notice any incorrect statement, please point it out.

Thanks
Rock31
 
a little correction:

integer*4 , allocatable :: data:))
character*1 , allocatable :: x:))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top