简体   繁体   中英

Convert Big-Endian struct to Little-Endian C++

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM