Convert Little Endian to Big Endian

前端 未结 13 1865
慢半拍i
慢半拍i 2020-11-27 16:34

I just want to ask if my method is correct to convert from little endian to big endian, just to make sure if I understand the difference.

I have a number which is st

13条回答
  •  广开言路
    2020-11-27 16:38

    You can use the lib functions. They boil down to assembly, but if you are open to alternate implementations in C, here they are (assuming int is 32-bits) :

    void byte_swap16(unsigned short int *pVal16) {
    
    //#define method_one 1
    // #define method_two 1
    #define method_three 1
    #ifdef method_one
        unsigned char *pByte;
    
        pByte = (unsigned char *) pVal16;
        *pVal16 = (pByte[0] << 8) | pByte[1];
    #endif
    
    #ifdef method_two
        unsigned char *pByte0;
        unsigned char *pByte1;
    
        pByte0 = (unsigned char *) pVal16;
        pByte1 = pByte0 + 1;
        *pByte0 = *pByte0 ^ *pByte1;
        *pByte1 = *pByte0 ^ *pByte1;
        *pByte0 = *pByte0 ^ *pByte1;
    #endif
    
    #ifdef method_three
        unsigned char *pByte;
    
        pByte = (unsigned char *) pVal16;
        pByte[0] = pByte[0] ^ pByte[1];
        pByte[1] = pByte[0] ^ pByte[1];
        pByte[0] = pByte[0] ^ pByte[1];
    #endif
    
    
    }
    
    
    
    void byte_swap32(unsigned int *pVal32) {
    
    #ifdef method_one
        unsigned char *pByte;
    
        // 0x1234 5678 --> 0x7856 3412  
        pByte = (unsigned char *) pVal32;
        *pVal32 = ( pByte[0] << 24 ) | (pByte[1] << 16) | (pByte[2] << 8) | ( pByte[3] );
    #endif
    
    #if defined(method_two) || defined (method_three)
        unsigned char *pByte;
    
        pByte = (unsigned char *) pVal32;
        // move lsb to msb
        pByte[0] = pByte[0] ^ pByte[3];
        pByte[3] = pByte[0] ^ pByte[3];
        pByte[0] = pByte[0] ^ pByte[3];
        // move lsb to msb
        pByte[1] = pByte[1] ^ pByte[2];
        pByte[2] = pByte[1] ^ pByte[2];
        pByte[1] = pByte[1] ^ pByte[2];
    #endif
    }
    

    And the usage is performed like so:

    unsigned short int u16Val = 0x1234;
    byte_swap16(&u16Val);
    unsigned int u32Val = 0x12345678;
    byte_swap32(&u32Val);
    

提交回复
热议问题