CFile:WriteBswap
The WriteBswap method writes binary data to a file and reverses the byte order in the process. This method is useful for writing binary data to a file that uses a reversed byte orderi, such as FITS format, or for writing files that are to be read on another computer that uses a reversed byte order architecture. Also see the Write method for writing data with a normal byte order.
nBytes = CFile:WriteBswap( value, sDataType )
nBytes = CFile:WriteBswap( table )
nBytes = CFile:WriteBswap( table, sDataType )
where
value is a value to be written to the file.
table is a Lua table of 1-dimension to be written to the file. The table cannot contain nested tables, must start at index [1], and must have sequential indices up through [ number of elements ].
sDataType is a string that specifies the data format used to write the value or the table elements to the file. When writing a table, sDataType is optional and defaults to "double" (i.e., 64-bit real values) if not specified.
The return value nBytes is the number of bytes written to the file.
This method can write single values or an entire data table to the CFile object. The format used in the output file is not necessarily the same as that of the value being written. For example, suppose value=12. Then you can write this value as an 8-, 16-, or 32-bit integer or a 32- or 64 bit real number by changing the sDataType string. See Data Types for a description of the available data types and the string to use for sDataType. Note that character strings do not have byte ordering issues, so both Write and the current method give the same result when writing string data.
The script below provides a complete function to save a Lua table to a raw binary file as 64-bit real numbers. The table is a simple array with indices [1] through [ nCols x nRows ].
The nCols and nRows parameters are written individually as "int" (32 bit) integers. Following that is a numeric Data Type code to indicate the table contains 64 bit real numbers. Then the entire table is saved. When using WriteBswap for a table, the output data type defaults to 64-bit real values if it is not specified. For the file to end up with the correct length, it is assumed that the number of table elements is nCols x nRows.
|
|
|
-- failure: a table was not passed |
|
-- Get a file name with file type "dat" |
|
-- check that a file name was selected |
|
-- Open the file for writing binary |
|
-- if the file was opened |
|
-- number of columns as a long integer |
|
-- number of rows as a long integer |
|
-- 6 = code for 64-bit real number |
|
-- write the table as 64-bit real |
|
-- close the file when done |
|
-- success |
|
|
|
|
|
-- failure |
|
|