• Status: Solved
• Priority: Medium
• Security: Public
• Views: 392

# endian explanation

hi all,

i got this function

#define LITTLE_ENDIAN 0
#define BIG_ENDIAN    1

int machineEndianness()
{
int i = 1;
char *p = (char *) &i;
if (p[0] == 1) // Lowest address contains the least significant byte
return LITTLE_ENDIAN;
else
return BIG_ENDIAN;
}

from wikipedia.com.

I understand the difference between little and big endian and their definition. However, i don't get the why author need to use
char *p = (char*) &i;  <--- why need to convert to char pointer type?
and compare condition p[0] ==1

Thanks for your help and patience.
0
valleytech
• 5
• 2
2 Solutions

Data Warehouse Architect / DBACommented:
Hi valleytech,

If you read the integer value, C will read all 4 (2/8) bytes and arrange them in mathematical (logical) order.  By recasting to a char, C will read only the first byte.  If the first byte is zero, the machine is Big Endian, if it is non-zero, the machine is Little Endian.

Good Luck!
Kent
0

Author Commented:
oh Kent
what do you mean  2/8? I just wonder int has 4 bytes and char has 1 byte in C? Am i right? Thanks.
0

Data Warehouse Architect / DBACommented:
Hi valleytech,

An int is 4 bytes on a 32-bit machine.  It's only 2 bytes on a 16-bit machine, but 8 bytes on a 64-bit one.  :~}

Kent
0

Author Commented:
Thanks Kent.
By the way, can you take a look at my recursive quesiton. Thanks a lot.
0

Commented:
Hi valleytech,

Imagine a 32bit number having value 1. In a little-endian machine it will be layed out in memory like this (in hex).

01 00 00 00

on a big-endian:

00 00 00 01

Now if you look at it as a byte sequence, reading the first byte will either give you a 1 or a 0 depending on the machine.

Paul
0

Author Commented:
Great. So i slipt each has 250 points .
Thanks a lot.
0

Author Commented:
both explanation are mutually affect and help me totally understand the problem. Thanks.
0

Author Commented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.