[ncl-talk] How to combine multiple bytes into numeric types
Dave Allured - NOAA Affiliate
dave.allured at noaa.gov
Fri Aug 15 17:25:09 MDT 2014
Li,
The best solution would be for NCL to support mixed data types in binary
files, like C and fortran. But that support is complicated, and not
currently available.
I think that it is dangerous to perform direct type conversions from byte
strings in a user program, if it can possibly be avoided.
The NCL function "fbindirread" reads a binary file as if it is a continuous
array of a single data type. You can use this ability to read mixed types
directly from the file, as long as the data are aligned correctly. This
example will read your header values correctly:
rec_num = 0
n_elements = 10
head_int = fbindirread ("test.bin", rec_num, n_elements, "integer")
b = head_int(4:5)
print ("b = " + b)
head_float = fbindirread ("test.bin", rec_num, n_elements, "float")
c = head_float(6:9)
print ("c = " + c)
Note that the header is read more than once. This is necessary when
reading mixed types by this method.
Note also that each integer and each float is 4 bytes long. To skip over
the 16 characters at the start of the header, you must skip over only 4
elements in an integer or float array, *not* 16 elements.
You are lucky that the authors of this file decided to make the character
string an even multiple of 4. Otherwise the integers and floats would be
misaligned. You could still read such a file with NCL, but it would
require more tricks and get messier. HTH.
--Dave
On Thu, Aug 14, 2014 at 12:36 AM, Li Dong <dongli at lasg.iap.ac.cn> wrote:
> Dear all,
>
> When I read a binary file, which contains a head, I first need to get some
> information from the head. The head contains several variables in different
> types, such as in Fortran:
>
> type head
> character(16) a
> integer(2) b
> real(4) c
> end head
>
>
> The binary file is written in C format (I think, it is from other guys). I
> tried to use `cbinread` to read the head as:
>
> head = cbinread(“…”, 22, “character”)
>
>
> So now I get an array of characters. The character string `a` can be
> easily extracted as:
>
> a = charactertostring(head(0:15))
>
>
> But what about `b` and `c`? How do I get them from head(16:17) and
> head(18:21)? I didn’t find some functions that can take several bytes and
> combine them to form other desired types.
>
> Thanks in advance!
>
> Best regards,
>
> Li
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mailman.ucar.edu/pipermail/ncl-talk/attachments/20140815/623acdef/attachment.html
More information about the ncl-talk
mailing list