将多个变量打包成一个字符串 [英] Packing multiple variable into one string
问题描述
字符流被发送到通信设备。为了可读性,我将个人配置写为变量:
A stream of chars are sent out to a communication device. For readability purposes, i wrote inidividual configurations as variables:
unsigned char a1;
unsigned char a2;
unsigned char a3;
unsigned char a4;
unsigned char a5;
std::string a6;
unsigned char a7;
unsigned char a8;
什么是最好的方式将它包装到一个变量,使它完美对齐?
到现在我想到把一切都变成 struct
。
What is the best way to pack it into a variable tightly so that it's aligned perfectly?
Till now I've think of put everything into a struct
.
/ strong>: struct
看起来不像一个可行的选项,因为 struct
不支持 string
,并且字符串的大小是变化的,虽然是一次声明的东西。在GCC中编译
edit: struct
doesn't look like a viable option since struct
doesn't hold string
, and string is varying in size, although is a one time declared thing. Compiled in GCC
edit2 :使用打包的 struct
方法,首先将 string
更改为 c_str
。
edit2: Gonna go with packed struct
method, but will convert the string
to a c_str
first. Until a better answer, this is the way to be.
推荐答案
A 打包结构 ,而不仅仅是一个结构会更合适。
A packed structure, rather than just a structure would be more appropriate.
编辑:当然,你不应该使用 string
作为你的结构的一部分,正如其他人所指出的。您应该使用 str.c_str());
将 string
转换为字符数组,然后将其存储在打包结构。
Ofcourse, you should not use string
as a part of your structure, It skipped me while answering but as others have pointed out. You should conver string
to character array using str.c_str());
and then store the same in the packed structure.
这篇关于将多个变量打包成一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!