0

我想通过网络发送一些整数(int32_t)。

为此,我首先转换整数并发送它们。

p.x = 129;
p.y = 42;
p.d = counter++;

converted[0] = htonl(p.x);
converted[1] = htonl(p.y);
converted[2] = htonl(p.d);
if ( (bytes = send(socket, (char *)converted, pointSize, 0)) < 0)
        {
            std::cerr << "bytes = " << bytes << std::endl;
        }

然后 Qt 应该完成这项工作,所以我尝试了 QDataStream 转换,但失败了,值 > 128 为负数。所以目前我做了这样的转换:

   while ( socket->bytesAvailable() > 0 )
   {
       //qDebug() << "Data received" << socket->bytesAvailable();
       m_data.append(socket->readAll());
       //qDebug() << "Buffer " << m_data.size();
       if (m_data.size() >= sizeOfPoint)
       {
           Point x;
           QByteArray b = m_data.left(sizeOfPoint);
           for (int i = 0; i < 4; i++)
           {
               x.x += (u_int8_t) b[i] << 8*(3-i);
           }
           for (int i = 4; i < 8; i++)
           {
               x.y += (u_int8_t) b[i] << 8*(7-i);
           }
           for (int i = 8; i < 12; i++)
           {
               x.d += (u_int8_t) b[i] << 8*(11-i);
           }

           //x.x = (u_int8_t) (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | (b[3]);
           //x.y = (b[4] << 24) | (b[5] << 16) | (b[6] << 8) | (b[7]);
           //x.d = (b[8] << 24) | (b[9] << 16) | (b[10] << 8) | b[11];
           //x.d = b[10] << 8;
           //x.d = (b[11]);

           //QDataStream in(buffer.data());
           //in.setByteOrder(QDataStream::LittleEndian);
           //in >> conv[1];
           //in >> conv[2];

           qDebug() << "Data provided " << x.x << " " << x.y << " "<< x.d;
            m_data.remove(0, sizeOfPoint);
       }
   }

转换这些整数的最佳方法是什么,for 循环对我来说似乎不是最优的。

谢谢

4

0 回答 0