Big endian test

Possible duplicate:
Small vs. Large Endians: How to interpret the test

Is there an easy way to test the code using gcc or any online compiler like ideone for big endian? I don't want to use qemu or virtual machines

EDIT

Can someone explain the behavior of this piece of code on the system using big end?

#include <stdio.h>
#include <string.h>
#include <stdint.h>

int main (void)
{
    int32_t i;
    unsigned char u[4] = {'a', 'b', 'c', 'd'};

    memcpy(&i, u, sizeof(u));
    printf("%d\n", i);
    memcpy(u, &i, sizeof(i));
    for (i = 0; i < 4; i++) {
        printf("%c", u[i]);
    }
    printf("\n");
    return 0;
}

      

+3


source to share


1 answer


How is the program?

#include <stdio.h>
#include <stdint.h>

int main(int argc, char** argv) {
    union {
       uint32_t word;
       uint8_t bytes[4];
    } test_struct;
    test_struct.word = 0x1;
    if (test_struct.bytes[0] != 0)
        printf("little-endian\n");
    else
        printf("big-endian\n");
    return 0;
}

      

In little-endian architecture, the least significant byte is stored first. In a big end architecture, the most significant byte is stored first. That way, by superimposing a uint32_t

on a uint8_t[4]

, I can check that the first byte comes first. See: http://en.wikipedia.org/wiki/Big_endian

GCC specifically defines a macro __BYTE_ORDER__

as an extension. You can test against __ORDER_BIG_ENDIAN__

, __ORDER_LITTLE_ENDIAN__

and __ORDER_PDP_ENDIAN__

(which I didn't know!) - see http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html

See also http://en.wikipedia.org/wiki/Big_endian




As for running code in an endianness that doesn't fit your intrinsic nature of your computer, then you have to compile and run it on an architecture with such varying degrees of precision. Thus, you will need to cross-compile and run on an emulator or virtual machine.




edit : ah, I haven't seen the first one printf()

.

The first printf

will print "1633837924" since the big end machine will interpret the character 'a'

as the most significant byte in an int.

The second one printf

will just print "abcd" since the value u

was copied byte by byte back and forth from i

.

+3


source







All Articles