Home > Enterprise >  string into const uint8_t*
string into const uint8_t*

Time:08-07

I'm writing a program in C /C for raspberry pi pico. 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. 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*__.

CodePudding user response:

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

reinterpret_cast<const unsigned char*>(&f)

and the contents of a std::string variable called s via

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).

This is assuming of course that you want to store the object representation of the float variable. If you want to store a serialized representation instead, then first convert to a std::string in an appropriate format.


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. They would then cause aliasing violations and therefore undefined behavior when the values are accessed through the resulting pointers.

  • Related