Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union and endianness

Tags:

c

cpu

endianness

typedef union status
{
    int nri;
    char cit[2];
}Status;

int main()  {
    Status s;
    s.nri = 1;
    printf("%d \n",s.nri);
    printf("%d,%d,\n",s.cit[0],s.cit[1]);
}

OUTPUT:

1
0,1

I know this output on the second line is depend on the endianess of the CPU. How I can write such in a platform-independant program? Is there any way of checking the endianess of the CPU?

like image 746
Vallabh Patade Avatar asked Sep 18 '13 04:09

Vallabh Patade


1 Answers

You can use htonl() and/or ntohl(). htonl() stands for "host to network long", while ntohl() stands for "network to host long". The "host" and "network" refers to the byte order. Network byte order is "big-endian". The operations will be no-ops if the host platform is also "big-endian". Using these routines, the following program will always report the same output:

uint32_t x = htonl(1);
unsigned char *p = (void *)&x;
printf("%u %u %u %u\n", p[0], p[1], p[2], p[3]);
uint32_t y = ntohl(x);
assert(y == 1);
like image 181
jxh Avatar answered Oct 22 '22 21:10

jxh