【问题标题】:how should i convert a uint32_t value into a char array of size 32?我应该如何将 uint32_t 值转换为大小为 32 的 char 数组?
【发布时间】:2017-07-14 03:07:13
【问题描述】:

(uint32_t header;char 数组[32];) 如何在 c++ 中将数据从标头复制到数组?如何进行这种转换?我尝试了类型转换,但它似乎不起作用。

【问题讨论】:

  • uint32 是 32 位。 char[32] 是 32 * 8 位。所以问题是,您实际上想做什么?您认为应该如何进行这样的转换?
  • 我其实是想把uint32数据以字符数组的形式存起来
  • 大小可以适当调整
  • 但这意味着什么?是否要将array[0] 映射到header 的8 个最高有效位,并将array[3] 映射到header 的8 个最低有效位,并用0 填充array[4]array[31]? ......这不是那么直观......
  • 那么,你想让array[0] 之类的东西成为'0''1' 基于header 位0,array[1] 基于位1,等等?跨度>

标签: c++ arrays char uint32-t


【解决方案1】:

使用std::bitset 获取二进制表示并将其转换为字符数组:

#include <iostream>
#include <cstdint>
#include <bitset>

int main()
{
    std::uint32_t x = 42;
    std::bitset<32> b(x);
    char c[32];
    for (int i = 0; i < 32; i++)
    {
        c[i] = b[i] + '0';
        std::cout << c[i];
    }
}

这将类似于 little-endian 表示。

【讨论】:

    【解决方案2】:

    我知道这个问题有点老了,但我会写一个可能对其他人有帮助的答案。所以,基本上你可以使用std::bitset,它代表一个固定大小的N位序列。

    使用std::bitset&lt;32&gt; bits(value),您可以创建一个表示 4 字节整数的 32 位序列。您还可以使用std::bitset::to_string 函数将这些位转换为std::string

    但是,如果您想获得更复杂的输出,可以使用以下函数:

    void u32_to_binary(uint32_t const& value, char buffer[]) {
        std::bitset<32> bits(value);
        auto stringified_bits = bits.to_string();
    
        size_t position = 0;
        size_t width = 0;
        for (auto const& bit : stringified_bits) {
            width++;
            buffer[position++] = bit;
    
            if (0 == width % 4) {
                buffer[position++] = ' ';
                width = 0;
            }
        }
    
        buffer[position] = '\0';
    }
    

    这将创建一个这样的输出:

    0000 0000 0000 0000 0000 0000 0001 1100
    

    这里是你如何使用它:

    #include <iostream>
    #include <bitset>
    
    int main() {
        char buff[128];
        u32_to_binary(28, buff);
        std::cout << buff << std::endl;
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 1970-01-01
      • 2018-04-30
      • 2012-05-25
      • 2015-08-03
      • 1970-01-01
      • 2013-12-02
      • 2011-06-08
      • 2022-01-22
      相关资源
      最近更新 更多