联盟和字节顺序 [英] Union and 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:
OUTPUT:
1
0,1
我知道在第二行此输出取决于CPU的字节序。我怎么能在一个平台无关的程序写这样?是否有检查CPU的字节序的方法吗?
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?
推荐答案
您可以使用 htonl()
和/或 ntohl()
。 htonl()
表示主机到网络长,而 ntohl()
表示网络到主机长 。 主机和网络指的是字节顺序。网络字节顺序是大端。该操作将是空操作如果主机平台也是大端。使用这些程序时,下面的程序将始终报告相同的输出:
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);
这篇关于联盟和字节顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!