Union and endianness

有些话、适合烂在心里 提交于 2020-01-01 10:02:18

问题


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?


回答1:


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);



回答2:


If you want endian-independent code, then you want platform-indepentent code as well, otherwise your requirements don't make sense. Code which does not rely on endianess cannot rely of the size of an int, nor on the signedness of char.

To get something truly portable, I suppose you would have to write something similar to this:

#include <stdio.h>
#include <stdint.h>

#define INT_BITS (sizeof(int) * 8)

#define BYTE0_MASK (0xFFu << (INT_BITS -  8))
#define BYTE1_MASK (0xFFu << (INT_BITS - 16))

int main()
{
  int i = 0xAABBCCDD;
  unsigned char arr [2] =
  {
    (i & BYTE0_MASK) >> (INT_BITS -  8),
    (i & BYTE1_MASK) >> (INT_BITS - 16)
  };

  printf("%x %x", arr[0], arr[1]);    
}



回答3:


Endianness is usually not an issue if your program does not communicate with other program (including the same program written for another platform), unless you do something very special like the union defined in your question. When your program does communicate with other programs, like saving binary data into a file, sending data in a socket, it'd be better to define the endianness clearly in the format/protocol. Alternatively you can also transmit the data in textual form.



来源:https://stackoverflow.com/questions/18863913/union-and-endianness

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!