2

我在 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 的内容不会改变。我试图在谷歌上找到 swaw,用于交换单词,但没有成功。是否已弃用?

4

2 回答 2

3

对于您想要的网络htonlhtons以及它们的同伴ntohl,以及ntohs32 位和 16 位整数的主机到网络和网络到主机转换。这些将针对您所在的架构进行适当的定义。因此,在 SPARC 上,它们将成为无操作(大端平台),而在 x86 上,它们被实现为交换。他们来自<arpa/inet.h><netinet/in.h>

于 2013-06-04T02:36:32.090 回答
0

我找到的最简单的解决方案是使用此处描述的 FIX_INT(x) 。

于 2013-06-04T02:14:07.657 回答