Reputation: 374
I am working on a parser code to read all the data from a binary file. Incidentally the binary file is in Big-Endian.
When I read the binary header of the file I read it into a Structure
through this method:
Structure:
struct BinaryHeader{
int jobID;
int lineNumber;
int reelNumber;
short unsigned int tracesPerEnsemble;
short int aTracesPerEnsemble;
short unsigned int sampleInterval;
short unsigned int sampleIntervalOriginalFieldRec;
short unsigned int samplesPerTrace;
short unsigned int samplesPerTraceOriginalFieldRec;
...etc.
Parsing method:
void Segy::parseSegyFile(){
char textHeader[3200]; //to skip the first 3200 byte
ifs.read(textHeader,sizeof(textHeader));
BinaryHeader binaryHeader;
ifs.read(reinterpret_cast<char *>(&binaryHeader), sizeof(binaryHeader));
}
}
As I mentioned the endianness is Big-Endian, I found this answer for the conversion and it works like a charm but when -- for exapmle -- I print out the binaryHeader I always have to swap the sequence of the bytes.
std::cout << std::left << std::setw(w) << "JobID:" << std::fixed << SwapEnd(binaryHeader.jobID) << std::endl
Question: Is there any elegant way to convert the whole binaryHeader to Little-Endian?
Upvotes: 3
Views: 1555
Reputation: 14119
Well I do not know if this is elegent to you but boost::fusion might help you.
struct BinaryHeader{
int jobID;
int lineNumber;
int reelNumber;
...
};
BOOST_FUSION_ADAPT_STRUCT(
BinaryHeader,
jobID,
lineNumber,
reelNumber
...
)
struct EndianSwap
{
template<typename T>
void operator()(T& t) const
{
SwapEnd(t);
}
};
then after reading a BinaryHeader
in big endian just do this.
boost::fusion::for_each(b, EndianSwap());
Upvotes: 1