如何将 Boost C++ 中接收到的字节转换为 unsigned int 和 unsigned int 向量

How to convert received bytes in Boost C++ to a unsigned int and to a vector of unsigned int

我正在通过 Python TCP 套接字向用 Boost C++ 编写的客户端发送一个无符号整数。 我想知道如何将 Boost C++ 套接字中接收到的字节转换为无符号整数。

Python 套接字服务器

import socket
import struct

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print("listening..")
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)

        # SENDING 10 AS AN UNSIGNED INTEGER
        conn.send(struct.pack("I",10))

C++ Boost 客户端套接字

#include <boost/asio/local/stream_protocol.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>

using namespace std;

// CREATE SOCKET
boost::asio::io_service io_context;
boost::asio::streambuf sb;
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 10000);
boost::asio::ip::tcp::socket socket(io_context);
socket.connect(ep);

// READ 4 BYTES
boost::asio::read(objSocket, sb,boost::asio::transfer_exactly(4), ec))

cout << "\nreceived: '" << &sb << "'\n";

// CONVERT 4 BYTES TO UNSIGNED INT
boost::asio::streambuf::const_buffers_type bufs = sb.data();

string str(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + sb.size());

sb.consume(sb.size());

std::stringstream sstr(str);

unsigned int receivedInt = 0;

sstr >> receivedInt;

cout << "\nReceivedInt: "<< length;

PS: C++ 客户端收到数据(4bytes)但我无法将其转换为uint。

以及如何将 bytes 转换为 unsigned int 向量?

提前致谢!

在 Python 端,您没有为字节流指定字节顺序。所以这取决于机器,它可能是 little-endianbig-endian。这可能会导致问题。

您可以通过以下方式强制发送字节流,例如 little-endian

conn.send(struct.pack("<I",10))    # added < 

在 C++ 中,通过调用 sstr >> receivedInt,您可以执行 格式化 数据读取。如果您的流将“10”保存为字符串 - 2 个字符,但您的流包含 4 个字节 - 10 的二进制表示形式为十进制,它可能会起作用。您只需将所有字节的值合并到 unsigned int,这很容易,因为您知道字节的顺序:

boost::asio::streambuf::const_buffers_type bufs = sb.data();
string str(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + sb.size());
sb.consume(sb.size());
uint32_t received = 
    (str[0] & 0xFF) 
  | (str[1] << 8) & 0xFF00 
  | (str[2] << 16) & 0xFF0000
  | (str[3] << 24);
std::cout << received << std::endl;  // 10 

数据以 little-endian 顺序发送,因此在将其合并到 uint32 数据时必须像这样移动:

[str[3] | str[2] | str[1] | str[0]]

在移动 char 之前提升为 int 并扩展了一点符号,因此您必须使用适当的掩码执行按位 AND将最左边的位归零。