On 8/4/07, Jan Andersson <[EMAIL PROTECTED]> wrote:
> On 8/4/07, Anup Joshi <[EMAIL PROTECTED]> wrote:
> > thank you all of you for your responses but i still cant get one thing, i 
> > was successfully able to compile my recent code on gcc v3.42 also, here is 
> > the code again:
> >
> >  =====
> >  #include <stdio.h>
> >
> >  union vals {
> >      unsigned short x;
> >      unsigned char y[2];
> >  } myvals;
> >
> >  int main() {
> >      myvals.y[0] = 1;  //lsb
> >      myvals.y[1] = 21; //msb
> >
> >  printf("%d", myvals.x);
> >      printf("\n %d", sizeof(myvals));
> >  }
> >
> >  compiled using command: gcc union.c -o myunion.exe
> >  ====
> >  and output again is
> >  5377
> >   2
> >  =====
> >  so according to Vic i havent solved the endian problem but i cant 
> > understand where the problem actually is in this code ???
>
<snip>

My previous reply might have been a bit... long :-) If my previous
post was confusing perhaps this small program will clear things up:

#include <stdio.h>

int main(void)
{
  int number = 0x0A0B0C0D;
  char *ptr = (char*)&number;
  int i;

  printf("We have stored the number %08X at address %p\n",
         number, &number);

  for (i = 0; i < 4; i++)
    printf("Value %02X is at byte offset %d (address %p)\n", *(ptr +
i), i, ptr + i);

  return 0;
}

If we run this on a little endian system we get:

We have stored the number 0A0B0C0D at address 0xbf91b1c8
Value 0D is at byte offset 0 (address 0xbf91b1c8)
Value 0C is at byte offset 1 (address 0xbf91b1c9)
Value 0B is at byte offset 2 (address 0xbf91b1ca)
Value 0A is at byte offset 3 (address 0xbf91b1cb)

An example run from a big endian system (Sun SPARC processor):

We have stored the number 0A0B0C0D at address ffbff7ac
Value 0A is at byte offset 0 (address ffbff7ac)
Value 0B is at byte offset 1 (address ffbff7ad)
Value 0C is at byte offset 2 (address ffbff7ae)
Value 0D is at byte offset 3 (address ffbff7af)

Best regards,
  Jan

Reply via email to