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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With