意外的大端转换输出

时间:2015-07-18 14:42:40

标签: c++ type-conversion endianness

我正在使用libflac,我需要将我的数据从little endian转换为big endian。但是在我的一个测试代码中,我没有达到我的期望。我正在使用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 = transform [1]&lt;&lt; 8 |变换[0];

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

1 个答案:

答案 0 :(得分:0)

问题出在这一行

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];

但为什么不写一个函数进行endian转换呢?

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

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