1 // endian_example.cpp -------------------------------------------------------//
3 // Copyright Beman Dawes, 2006
5 // Distributed under the Boost Software License, Version 1.0.
6 // See http://www.boost.org/LICENSE_1_0.txt
8 // See library home page at http://www.boost.org/libs/endian
10 //----------------------------------------------------------------------------//
12 #define _CRT_SECURE_NO_DEPRECATE // quiet VC++ 8.0 foolishness
17 #include <boost/integer/endian.hpp>
19 using namespace boost::integer
;
23 // This is an extract from a very widely used GIS file format. I have no idea
24 // why a designer would mix big and little endians in the same file - but
25 // this is a real-world format and users wishing to write low level code
26 // manipulating these files have to deal with the mixed endianness.
33 little32_t shape_type
;
36 const char * filename
= "test.dat";
41 assert( sizeof( header
) == 16 ); // requirement for interoperability
45 h
.file_code
= 0x04030201;
46 h
.file_length
= sizeof( header
);
48 h
.shape_type
= 0x04030201;
50 // Low-level I/O such as POSIX read/write or <cstdio> fread/fwrite is sometimes
51 // used for binary file operations when ultimate efficiency is important.
52 // Such I/O is often performed in some C++ wrapper class, but to drive home the
53 // point that endian integers are often used in fairly low-level code that
54 // does bulk I/O operations, <cstdio> fopen/fwrite is used for I/O in this example.
58 if ( !(fi
= std::fopen( filename
, "wb" )) ) // MUST BE BINARY
60 std::cout
<< "could not open " << filename
<< '\n';
64 if ( std::fwrite( &h
, sizeof( header
), 1, fi
) != 1 )
66 std::cout
<< "write failure for " << filename
<< '\n';
72 std::cout
<< "created file " << filename
<< '\n';