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!

extract one byte from real 1

Status
Not open for further replies.

dongli

Technical User
Aug 30, 2009
9
CN
Hi,

I want to extract one specific byte from a 4-bytes real variable. How to do it?

For example:

real :: a = 42
integer(1) :: b

a: 01000010001010000000000[00000000] -> b


Thanks for help!
 
Depends on which version of Fortran you're using.

F77: use equivalence
Code:
      real a
      character*4 b
      integer c
      equivalence (a,b)
      a = 42.0
! This depends on the endianess: you might want b(4) or b(1)
      c = b(4)
      print *, c
F90 and above, use transfer function
 
Thanks xwb, it works!

real a
integer(1) b(4)

b = transfer(a, b)

BUT, b(1) is the lowest byte of a, and b(4) is the highest one. The order is a little strange.
 
It depends on the endianess of your underlying architecture. In an 8 byte sequence, the order can be

12 34 56 78
43 21 87 65
21 43 65 87 <-- this normally happpens on 16 bit machines

It varies a lot and is not portable. It looks like your machine has the 2nd variant.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top