c++ - Serialize/deserialize unsigned char -
i'm working on api embedded device, , need display image generated (by api). screen attached device allows me render bitmaps, data stored unsigned char image[] = { 0b00000000, 0b00001111, 0b11111110... }.
what easiest way deserialize string in whatever format needed?
my approach create stringstream, separate comma , push vector<char>. however, function render bitmaps accept char, , can find online seems quite difficult convert it. ideally, i'd rather not use vector @ all, including adds several kbs project, limited in size both download speed of embedded device (firmware transferred edge) , onboard storage.
from comments, sounds want convert string composed of series of "0b00000000" style literals, comma separated, array of actual values. way to:
- get number of bytes in image (i assume known string length?).
- create
std::vectorofunsigned charhold results. - for each byte in input, construct
std::bitsetstring value, , actual value.
here's code example. since have said you'd rather not use vector have used c-style arrays , strings:
#include <bitset> #include <cstring> #include <iostream> #include <memory> int main() { auto input = "0b00000000,0b00001111,0b11111111"; auto length = strlen(input); // number of bytes string length. each byte takes 10 chars // plus comma separator. int size = (length + 1) / 11; // allocate memory hold result. std::unique_ptr<unsigned char[]> bytes(new unsigned char[size]); // populate each byte individually. (int = 0; < size; ++i) { // create bitset. stride 11, , skip first 2 characters // skip 0b prefix. std::bitset<8> bitset(input + 2 + * 11, 8); // store resulting byte. bytes[i] = bitset.to_ulong(); } // loop on each byte, , output confirm result. (int = 0; < size; ++i) { std::cout << "0b" << std::bitset<8>(bytes[i]) << std::endl; } }
Comments
Post a Comment