gpt4 book ai didi

c++ - 如何将字符数组转换为基于字符串的十六进制流 (ostringstream)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:54:37 27 4
gpt4 key购买 nike

在 C++ 中(在带有 gcc 的 Linux 上)我想将字节数组 ( vector<unsigned char> ) 放入 ostringstream 中或 string .

我知道我可以使用 sprintf但它似乎不是使用 char* 的最佳方式还有。

顺便说一句:this link did not help

编辑: 到目前为止,所有答案都有效。但我并不是说我想将字节/十六进制值转换为它们的字符串表示形式,例如 vector<..> = {0,1,2} -> string = "000102" .抱歉缺少但重要的细节

最佳答案

获得赞成票的机会很小,但由于它正是 OP 所要求的,而且没有其他答案,包括选定的答案,奇怪的是,这样做:

#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>

// used by bin2hex for conversion via stream.
struct bin2hex_str
{
std::ostream& os;
bin2hex_str(std::ostream& os) : os(os) {}
void operator ()(unsigned char ch)
{
os << std::hex
<< std::setw(2)
<< static_cast<int>(ch);
}
};

// convert a vector of unsigned char to a hex string
std::string bin2hex(const std::vector<unsigned char>& bin)
{
std::ostringstream oss;
oss << std::setfill('0');
std::for_each(bin.begin(), bin.end(), bin2hex_str(oss));
return oss.str();
}

// or for those who wish for a C++11-compliant version
std::string bin2hex11(const std::vector<unsigned char>& bin)
{
std::ostringstream oss;
oss << std::setfill('0');
std::for_each(bin.begin(), bin.end(),
[&oss](unsigned char ch)
{
oss << std::hex
<< std::setw(2)
<< static_cast<int>(ch);
});
return oss.str();
}

备用流转储

如果您只想转储一个 unsigned char 固定数组,下面的操作将轻松完成,几乎没有任何开销。

template<size_t N>
std::ostream& operator <<(std::ostream& os, const unsigned char (&ar)[N])
{
static const char alpha[] = "0123456789ABCDEF";
for (size_t i=0;i<N;++i)
{
os.put(alpha[ (ar[i]>>4) & 0xF ]);
os.put(alpha[ ar[i] & 0xF ]);
}
return os;
}

当我想将固定缓冲区转储到 ostream 导数时,我一直使用它。调用非常简单:

unsigned char data[64];
...fill data[] with, well.. data...
cout << data << endl;

关于c++ - 如何将字符数组转换为基于字符串的十六进制流 (ostringstream),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3802059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com