[英]string into const uint8_t*
I'm writing a program in C++/C for raspberry pi pico.我正在用 C++/C 为树莓派 pico 编写一个程序。 Pico has a 2MB of flash memory and it's SDK provides a function which allows to write data to that memory:
Pico has a 2MB of flash memory and it's SDK provides a function which allows to write data to that memory:
void flash_range_program(uint32_t flash_offs, const uint8_t *data, size_t count)
Second parameter of that function is the data which we want to write in the memory. function 的第二个参数是我们要写入 memory 的数据。 I want to save strings and floats in that memory, but I don't know what is the best (performance wise) way to convert
std::string
and float
to __const uint8_t*__
.我想在 memory 中保存字符串和浮点数,但我不知道将
std::string
和float
转换为__const uint8_t*__
的最佳(性能方面)方法是什么。
Assuming that std::uint8_t
is unsigned char
(as is usually the case), you are allowed to simply access the object representation of a float
variable called f
via假设
std::uint8_t
是unsigned char
(通常是这种情况),您可以简单地访问名为f
的float
变量的 object 表示形式
reinterpret_cast<const unsigned char*>(&f)
and the contents of a std::string
variable called s
via以及名为
s
的std::string
变量的内容
reinterpret_cast<const unsigned char*>(s.c_str())
The corresponding sizes are sizeof(f)
and s.size()
(or s.size()+1
if you want to store the null terminator of the string as well).相应的大小是
sizeof(f)
和s.size()
(或者s.size()+1
如果您还想存储字符串的 null 终止符)。
This is assuming of course that you want to store the object representation of the float
variable.这当然是假设您要存储
float
变量的 object 表示形式。 If you want to store a serialized representation instead, then first convert to a std::string
in an appropriate format.如果您想存储序列化表示,则首先转换为适当格式的
std::string
。
In the unlikely scenario that uint8_t
is not an alias for unsigned char
you are not allowed to substitute unsigned char
with uint8_t
in the shown casts.在
uint8_t
不是unsigned char
的别名的不太可能的情况下,您不允许在显示的强制转换中用uint8_t
替换unsigned char
。 They would then cause aliasing violations and therefore undefined behavior when the values are accessed through the resulting pointers.然后,当通过结果指针访问值时,它们会导致别名违规,从而导致未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.