简体   繁体   中英

Unexpected big endian conversion output

I am using libflac and I need to convert my data from little endian to big endian. However in one of my test code i am not getting what I expect. I am using 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;
}

output:

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

When I do big_endian = transform[1] << 8 | transform[0];

I'd expect to see 93 192 0 0 or 0 0 93 192, what's going on?

The problem is in this line

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

transform[0] is keeping the LSB in little endian. When you do transform[1] << 8 | transform[0] transform[1] << 8 | transform[0] you store it in the LSB position, therefore it doesn't move anywhere and is still the lowest byte. The same to transform[1] which is the second byte and it's still the second byte after shifting.

Use this

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

or

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

But why don't just write a function for endian conversion?

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

or use the ntohl / ntohs function that is already available on every operating systems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM