Solved

# endian explanation

Posted on 2006-06-02
388 Views
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
Question by:valleytech

LVL 45

Assisted Solution

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 Comment

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

LVL 45

Expert Comment

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 Comment

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

LVL 16

Accepted Solution

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 Comment

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

Author Comment

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

Author Comment

0

## Featured Post

### Suggested Solutions

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.