[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 389
  • Last Modified:

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
Asked:
valleytech
  • 5
  • 2
2 Solutions
 
Kent OlsenData 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
 
valleytechAuthor 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
 
Kent OlsenData 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
valleytechAuthor Commented:
Thanks Kent.
 By the way, can you take a look at my recursive quesiton. Thanks a lot.
0
 
PaulCaswellCommented:
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
 
valleytechAuthor Commented:
Great. So i slipt each has 250 points .
 Thanks a lot.
0
 
valleytechAuthor Commented:
both explanation are mutually affect and help me totally understand the problem. Thanks.
0
 
valleytechAuthor Commented:
please help on recursive question. Thanks.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now