我在Debian 7.0.0上的CodeBlocks 10.05上使用g ++。
回到90年代,我编写了以下函数来反转4字节整数的字节顺序。
/*******************************/
void ByteSwapInt(int *ipInteger)
/*******************************/
{
int iBuffer;
_swab( (char *)ipInteger, (char *)&iBuffer, 4 );
swaw((char *)&iBuffer, (char *)ipInteger, 4);
}
直到最近,它还有效。但我注意到swaw似乎不再做任何事情了。我通过扩展上面的函数来检查* ipInteger和iBuffer中各个字节的数组,从而检查了发生了什么
/*******************************/
void ByteSwapInt(int *ipInteger)
/*******************************/
{
int iBuffer;
int Int[4], Buf[4];
(Int[0]) = (*ipInteger >> 24) & 0xff; // high-order (leftmost) byte: bits 24-31
(Int[1]) = (*ipInteger >> 16) & 0xff; // next byte, counting from left: bits 16-23
(Int[2]) = (*ipInteger >> 8) & 0xff; // next byte, bits 8-15
(Int[3]) = *ipInteger & 0xff;
_swab( (char *)ipInteger, (char *)&iBuffer, 4 );
(Buf[0]) = (iBuffer >> 24) & 0xff; // high-order (leftmost) byte: bits 24-31
(Buf[1]) = (iBuffer >> 16) & 0xff; // next byte, counting from left: bits 16-23
(Buf[2]) = (iBuffer >> 8) & 0xff; // next byte, bits 8-15
(Buf[3]) = iBuffer & 0xff;
swaw((char *)&iBuffer, (char *)ipInteger, 4);
(Int[0]) = (*ipInteger >> 24) & 0xff; // high-order (leftmost) byte: bits 24-31
(Int[1]) = (*ipInteger >> 16) & 0xff; // next byte, counting from left: bits 16-23
(Int[2]) = (*ipInteger >> 8) & 0xff; // next byte, bits 8-15
(Int[3]) = *ipInteger & 0xff;
}
* ipInteger的内容不会改变。我试图在google上找到swaw,交换单词。它被弃用了吗?
答案 0 :(得分:3)
对于您想要htonl
,htons
及其随播广告ntohl
和ntohs
的网络,32位的主机到网络和网络到主机的转换和16位整数。这些将根据您所在的体系结构进行适当定义。因此,在SPARC上,他们将成为无操作(大端平台),而在x86上,它们被实现为交换。它们来自<arpa/inet.h>
或<netinet/in.h>
答案 1 :(得分:0)
我找到的最简单的解决方案是使用描述为here的FIX_INT(x)。