意外的大端转换输出

Unexpected big endian conversion output

我正在使用 libflac,我需要将我的数据从小端转换为大端。然而,在我的一个测试代码中,我没有得到我所期望的。我正在使用 g++

#include <iostream>
#include <stdlib.h>
#include <stdio.h>

int main() {
        unsigned char transform[4];
        unsigned char output[4];
        unsigned char temp;

        int normal = 24000;

        memcpy(output, &normal, 4);
        std::cout << (int)output[0] << " " << (int)output[1] << " " << (int)output[2] << " " << (int)output[3] << "\n";


        //FLAC__int32 big_endian;
        int big_endian;

        short allo = 24000;

        memcpy(transform, &allo, 2);  // transform[0], transform[1]
        std::cout << (int)transform[0] << " " << (int)transform[1] << "\n";

        //big_endian = (FLAC__int32)(((FLAC__int16)(FLAC__int8)transform[1] << 8) | (FLAC__int16)transform[0]); // whaaat, doesn't work...

        big_endian = transform[1] << 8 | transform[0];  // this also give 192 93 0 0  uh?
        memcpy(output, &big_endian, 4);

        std::cout << (int)output[0] << " " << (int)output[1] << " " << (int)output[2] << " " << (int)output[3] << "\n";
        // 192 93 0 0   uh?

        // this one works
        transform[3] = transform[0];
        transform[2] = transform[1];
        transform[0] = 0;
        transform[1] = 0;

        memcpy(&big_endian, transform, 4);

        memcpy(output, &big_endian, 4);

        std::cout << (int)output[0] << " " << (int)output[1] << " " << (int)output[2] << " " << (int)output[3] << "\n";
        // 0 0 93 192      (binary)93 << 8 | (binary)192 = 24000

        return 0;
}

输出:

192 93 0 0
192 93
192 93 0 0
0 0 93 192

当我做的时候 big_endian = 变换[1] << 8 |变换[0];

我希望看到 93 192 0 0 或 0 0 93 192,这是怎么回事?

问题出在这一行

big_endian = transform[1] << 8 | transform[0];

transform[0] 将 LSB 保持在小端。当您执行 transform[1] << 8 | transform[0] 时,您将它存储在 LSB 位置,因此它不会移动到任何地方并且仍然是最低字节。与transform[1]相同,是第二个字节,移位后仍然是第二个字节。

使用这个

big_endian = transform[0] << 8 | transform[1];

big_endian = transform[0] << 24 | transform[1] << 16 | transform[2] << 8 | transform[3];

但是为什么不直接写一个字节序转换函数呢?

unsigned int convert_endian(unsigned int n)
{
    return (n << 24) | ((n & 0xFF00) << 8) | ((n & 0xFF0000) >> 8) | (n >> 24);
}

或使用已在每个操作系统上可用的ntohl/ntohs功能