从 C++ 中的位表示形式初始化字符
Initialization of a char from bit representation in C++
我有一条消息,其中包含一个唯一的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);
我认为这不太容易出错,也不比你的方法慢。
有什么理由你喜欢先转换它吗?
相关文章:
- 使用 cin.get() 初始化字符数组
- 当我们不使用空字符显式初始化字符数组时,字符串的长度是多少?
- 从 C++ 中的位表示形式初始化字符
- 初始化字符*
- 澄清了 strcpy() 在像这样初始化字符数组时的工作 *Arr.
- 使用 auto 关键字初始化字符数组
- make_unique值是否初始化字符数组
- 正在从常量初始化字符数组
- 在类构造函数中初始化字符矩阵
- 如何使用整数值中的数字符号初始化字符数组
- 如何初始化字符的 2D 数组
- 初始化字符数组 - C 和 C++
- 无法初始化C++字符
- 如何使用字符串(字符数组)初始化字符指针,而不是使用整数数组初始化 int 指针
- 是否可以使用有条件选择的字符串文本初始化字符数组
- 初始化字符时空字符的重要性
- 如何使用十六进制数初始化字符数组
- 断言错误,即使在使用 new 初始化字符指针后也是如此
- 如何在C++中使用字符串文字初始化字符的动态数组
- 有没有办法使用位初始化字符