• C

Machine type.

How can I know the machine type
whether it is Big-Endian or Little-Endian programmatically.
LVL 1
bhatAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dircCommented:
Assuming a 32-bit machine:

#include <stdio.h>

main(int argc, char **argv)
{
    int i = 0x01020304;
    unsigned char buf[4];
    static unsigned char big[4] = { 0x1, 0x2, 0x3, 0x4};
    static unsigned char little[4] = { 0x4, 0x3, 0x2, 0x1 };

    memcpy(buf, &i, sizeof(buf));

    if (memcmp(buf, big, sizeof(buf)) == 0) {
        printf("Big Endian\n");
    } else if (memcmp(buf, little, sizeof(buf)) == 0) {
        printf("Little Endian\n");
    } else {
        printf("Unknown Layout\n");
    }
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ufolk123Commented:
One more small code

typedef union s
{
int i;
char c[4];
};

main()
{
s u;
u.i=0x11223344;
if(u.c==0x44)
      printf("Little Endian");
else
      printf("Big Endian");
}



ufolk123
0
ozoCommented:
Both routines seem to assume 32 bit int and 8 bit char,
u.c==0x44 is comparing a (char *) with an (int),
But even after that's fixed, I don't think the the C standard actually guarantees that the semantics of union members will work that way.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.