从 C++ 中的位表示形式初始化字符

Initialization of a char from bit representation in C++

本文关键字:初始化 字符 表示 C++      更新时间:2023-10-16

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

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

我可以使用函数 std::bitset::to_string(( 将每个位转换为 char;但是消息的大小将增加到 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 位(表示每个位。我想代表一点...一点点,不是字符。

谢谢

像这样的事情,不是唯一的方法

#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);

如果您只想使用 mpi 发送std::string msg,我会做这样的事情

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

我认为这不太容易出错,也不比你的方法慢。

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