-1

我有一条包含唯一 ID 的消息,以及我需要通过 MPI 进程发送的一些信息。为此,我将此消息转换为位数组。

我使用std::bitset类将一条消息转换为位表示。现在,我想用 MPI 将它发送到另一个进程。

我可以使用函数std::bitset::to_string()将每个位转换为字符;但是消息的大小将增加到 sizeof(char)*MSG_SIZE (在我的情况下,MSG_SIZE 等于 256)。

static const int MSG_SIZE = 256;
std::bitset<MSG_SIZE> msg;
msg = convert_to_bit(uint64_t uid, {additional information...});
// Using the function to_string(), my message is now of size (MSG_SIZE * sizeof(char))
// because each bit in the bitset is represented by a char (= 32 bits)
MPI_Send(msg.to_string().c_str(), msg.to_string().size(), MPI_BYTE, 1, 0, MPI_COMM_WORLD);

我怎样才能避免这种情况,保持消息的大小等于 256 位?

事实上,我想要这样的情况:

static const int MSG_SIZE = 256;
std::bitset<MSG_SIZE> msg;
msg = convert_to_bit(uint64_t uid, {additional information...});
// not necessary represented using char
// However I have no idea about which type I have to use
char* msg_in_bits = new char[MSG_SIZE / sizeof(char)];
msg_in_bits = do_something(msg);
MPI_Send(msg_in_bits, MSG_SIZE, MPI_BYTE, 1, 0, MPI_COMM_WORLD);

我只想发送一条消息的实际大小:MSG_SIZE = 256 位。不要增加我的消息的大小,因为我将用一个字符(= 32 位)表示每一位。我想代表一点……一点点,而不是一个字符。

谢谢

4

2 回答 2

1

像这样的东西,不是唯一的方法

#include <cstdint>

static const int MSG_SIZE = 256;
static const int MSG_SIZE_IN_BYTES = MSG_SIZE/8;
std::bitset<MSG_SIZE> msg = ...;
uint8_t msg_in_bits[MSG_SIZE_IN_BYTES] = {0};
for (int i = 0; i < MSG_SIZE; ++i)
    if (msg[i])
        msg_in_bits[i/8] |= 1 << (i%8);
MPI_Send(msg_in_bits, MSG_SIZE_IN_BYTES, MPI_BYTE, 1, 0, MPI_COMM_WORLD);
于 2018-08-21T09:23:18.403 回答
0

如果你只是想std::string msg用 mpi 发送一个,我会做这样的事情

MPI_Send(msg.c_str(), msg.size(), MPI_CHAR, 0, 0, MPI_COMM_WORLD);

我认为这比你的方法更不容易出错并且不慢。

你有什么理由喜欢先转换它吗?

于 2018-08-21T09:32:02.330 回答