[英]How should I read reverse-order bytes in C?
I need to read in unsigned char * bytes which are in reverse order to the native order. 我需要读取与本机顺序相反的无符号char *字节。 At the moment I have lots of little routines along the following lines: 目前,我有以下几条小例程:
uint8_t * bytes;
uint32_t r;
bytes = pt;
r = (((((bytes[0] << 8) + bytes[1]) << 8) + bytes[2]) << 8) + bytes[3];
pt += 4;
return r;
Is there a standard or portable way to do this kind of job, or do I have to hack up functions like this? 有没有一种标准的或可移植的方式来完成这种工作,或者我必须破解这样的功能?
The socket library for your platform provides the following functions which do these conversions: 您平台的套接字库提供了执行以下转换的以下功能:
ntohs
- Network to Host Short (16-bit) ntohs
网络主机短(16位) htons
- Host to Network Short (16-bit) htons
主机到网络的短地址(16位) ntohl
- Network to Host Long (32-bit) ntohl
主机长网络(32位) htonl
- Host to Network Long (32-bit) htonl
网络长主机(32位) To implement your code above, you can: 要实现上面的代码,您可以:
r = ntohl(*(uint32_t *)bytes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.