dealing with endianness in c++

后端 未结 5 1505
走了就别回头了
走了就别回头了 2020-12-17 05:44

I am working on translating a system from python to c++. I need to be able to perform actions in c++ that are generally performed by using Python\'s struct.unpack

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-17 06:06

    This falls in the realm of bit twiddling.

    for (i=0;i

    where mask == (sizeof type -1) if the stored and native endianness differ.

    With this technique one can convert a struct to bit masks:

     struct foo {
        byte a,b;       //  mask = 0,0
        short e;        //  mask = 1,1
        int g;          //  mask = 3,3,3,3,
        double i;       //  mask = 7,7,7,7,7,7,7,7
     } s; // notice that all units must be aligned according their native size
    

    Again these masks can be encoded with two bits per symbol: (1<, meaning that in 64-bit machines one can encode necessary masks of a 32 byte sized struct in a single constant (with 1,2,4 and 8 byte alignments).

    unsigned int mask = 0xffffaa50;  // or zero if the endianness matches
    for (i=0;i<16;i++) { 
         dst[i]=src[i ^ ((1<<(mask & 3))-1]; mask>>=2;
    }
    

提交回复
热议问题