我正在为嵌入式设备编写API,并需要显示(由API生成的)图像。连接到设备上的屏幕允许我呈现位图,数据存储为unsigned char image[] = { 0B00000000, 0B00001111, 0B11111110... }。
以任何格式反序列化字符串的最简单方法是什么?
我的方法是创建一个stringstream,用逗号分隔,然后推到vector<char>。然而,渲染位图的函数将只接受char,从我可以在网上找到的内容来看,转换它似乎相当困难。理想情况下,我宁愿根本不使用vector,因为它为项目添加了几个kbs,它的大小受到嵌入式设备的下载速度(固件通过EDGE传输)和车载存储的限制。
发布于 2016-01-06 00:18:05
从注释中可以看出,您希望将由一系列"0b00000000“样式文本(逗号分隔)组成的字符串转换为其实际值的数组。我这样做的方法是:
std::vector of unsigned char来保存结果。std::bitset,然后获取其实际值。下面是一个代码示例。既然您说过不使用vector,我就使用了C风格的数组和字符串:
#include <bitset>
#include <cstring>
#include <iostream>
#include <memory>
int main() {
auto input = "0b00000000,0b00001111,0b11111111";
auto length = strlen(input);
// Get the number of bytes from the string length. Each byte takes 10 chars
// plus a comma separator.
int size = (length + 1) / 11;
// Allocate memory to hold the result.
std::unique_ptr<unsigned char[]> bytes(new unsigned char[size]);
// Populate each byte individually.
for (int i = 0; i < size; ++i) {
// Create the bitset. The stride is 11, and skip the first 2 characters
// to skip the 0b prefix.
std::bitset<8> bitset(input + 2 + i * 11, 8);
// Store the resulting byte.
bytes[i] = bitset.to_ulong();
}
// Now loop back over each byte, and output it to confirm the result.
for (int i = 0; i < size; ++i) {
std::cout << "0b" << std::bitset<8>(bytes[i]) << std::endl;
}
}https://stackoverflow.com/questions/34622256
复制相似问题