How do I convert a big-endian struct to a little endian-struct?

后端 未结 8 2004
一整个雨季
一整个雨季 2020-12-08 11:03

I have a binary file that was created on a unix machine. It\'s just a bunch of records written one after another. The record is defined something like this:



        
相关标签:
8条回答
  • 2020-12-08 11:52

    You also have to consider alignment differences between the two compilers. Each compiler is allowed to insert padding between members in a structure the best suits the architecture. So you really need to know:

    • How the UNIX prog writes to the file
    • If it is a binary copy of the object the exact layout of the structure.
    • If it is a binary copy what the endian-ness of the source architecture.

    This is why most programs (That I have seen (that need to be platform neutral)) serialize the data as a text stream that can be easily read by the standard iostreams.

    0 讨论(0)
  • 2020-12-08 11:58

    Something like this should work:

    #include <algorithm>
    
    struct RECORD {
        UINT32 foo;
        UINT32 bar;
        CHAR fooword[11];
        CHAR barword[11];
        UINT16 baz;
    }
    
    void ReverseBytes( void *start, int size )
    {
        char *beg = start;
        char *end = beg + size;
    
        std::reverse( beg, end );
    }
    
    int main() {
        fstream f;
        f.open( "file.bin", ios::in | ios::binary );
    
        // for each entry {
        RECORD r;
        f.read( (char *)&r, sizeof( RECORD ) );
        ReverseBytes( r.foo, sizeof( UINT32 ) );
        ReverseBytes( r.bar, sizeof( UINT32 ) );
        ReverseBytes( r.baz, sizeof( UINT16 )
        // }
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题