首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >序列化/反序列化无符号字符

序列化/反序列化无符号字符
EN

Stack Overflow用户
提问于 2016-01-05 22:20:43
回答 1查看 806关注 0票数 0

我正在为嵌入式设备编写API,并需要显示(由API生成的)图像。连接到设备上的屏幕允许我呈现位图,数据存储为unsigned char image[] = { 0B00000000, 0B00001111, 0B11111110... }

以任何格式反序列化字符串的最简单方法是什么?

我的方法是创建一个stringstream,用逗号分隔,然后推到vector<char>。然而,渲染位图的函数将只接受char,从我可以在网上找到的内容来看,转换它似乎相当困难。理想情况下,我宁愿根本不使用vector,因为它为项目添加了几个kbs,它的大小受到嵌入式设备的下载速度(固件通过EDGE传输)和车载存储的限制。

EN

回答 1

Stack Overflow用户

发布于 2016-01-06 00:18:05

从注释中可以看出,您希望将由一系列"0b00000000“样式文本(逗号分隔)组成的字符串转换为其实际值的数组。我这样做的方法是:

  1. 获取图像中的字节数(我假设这是从字符串长度?)。
  2. 创建一个std::vector of unsigned char来保存结果。
  3. 对于输入中的每个字节,从字符串值构造一个std::bitset,然后获取其实际值。

下面是一个代码示例。既然您说过不使用vector,我就使用了C风格的数组和字符串:

代码语言:javascript
复制
#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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34622256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档