我正在开发一个项目,其中RAM中数据的字节序很重要。如果它是大端,我需要将它转换为Little Endian。我写的这个简短的程序能否可靠地确定任何Linux系统的字节顺序?
另外,是什么决定了存储在RAM中的数据的字节顺序?
#include <stdio.h>
#include <stdint.h>
int main ()
{
// This program will determine the endianness
// of your system and print the result in human
// readable form to stdout
uint16_t n;
uint8_t *p;
n = 0x01;
p = (uint8_t *) &n;
if (p[0]) {
printf("Little Endian\n");
} else {
printf("Big Endian\n");
}
return 0;
}
答案 0 :(得分:2)
不要重新发明轮子。使用POSIX byteorder functions。
命名强>
htonl
,htons
,ntohl
,ntohs
- 在主机和网络字节顺序之间转换值<强>概要强>
#include <arpa/inet.h> uint32_t htonl(uint32_t hostlong); uint16_t htons(uint16_t hostshort); uint32_t ntohl(uint32_t netlong); uint16_t ntohs(uint16_t netshort);
<强>描述强>
htonl()
函数将无符号整数hostlong
从主机字节顺序转换为网络字节顺序。
htons()
函数将无符号短整数hostshort
从主机字节顺序转换为网络字节顺序。
ntohl()
函数将无符号整数netlong
从网络字节顺序转换为主机字节顺序。
ntohs()
函数将无符号短整数netshort
从网络字节顺序转换为主机字节顺序。在i386上,主机字节顺序首先是最低有效字节,而在因特网上使用的网络字节顺序是最高有效字节。
要检查您是否可以执行系统字节顺序:
if (htonl(1) == 1) {
// big endian
}
else {
// little endian
}