C++ 字节的十六进制值,单位为c++;到字符串(相当于linux中的od-x)?
我的目标是编写更简洁/有效的函数,将存储在内存中的值转换为十六进制字符串(例如,打印的值将取决于系统的endianness):C++ 字节的十六进制值,单位为c++;到字符串(相当于linux中的od-x)?,c++,string,hex,byte,endianness,C++,String,Hex,Byte,Endianness,我的目标是编写更简洁/有效的函数,将存储在内存中的值转换为十六进制字符串(例如,打印的值将取决于系统的endianness): #包括 #包括 #包括 #包括 #包括 模板 标准::字符串六进制数(常量T&x) { 返回std::string(reinterpret_cast(&x),sizeof(x)); } int main() { std::cout您可以这样做: template<typename T> std::string hexOf(const T& x) {
#包括
#包括
#包括
#包括
#包括
模板
标准::字符串六进制数(常量T&x)
{
返回std::string(reinterpret_cast(&x),sizeof(x));
}
int main()
{
std::cout您可以这样做:
template<typename T>
std::string hexOf(const T& x)
{
std::string rc;
rc.reserve(2 * sizeof(x));
for (unsigned char* it(reinterpret_cast<char const*>(&x)), end(it + sizeof(x));
it != end; ++it) {
rc.push_back((*it / 16)["0123456789abcdef"]);
rc.push_back((*it % 16)["0123456789abcdef"]);
}
return rc;
}
模板
标准::字符串六进制数(常量T&x)
{
std::字符串rc;
钢筋混凝土储备(2*x);
对于(unsigned char*it(reinterpret_cast(&x)),end(it+sizeof(x));
它!=结束;++它){
rc.推回((*it/16)[“0123456789abcdef”);
rc.推回((*it%16)[“0123456789abcdef”);
}
返回rc;
}
以下是标准答案:
template <typename T>
std::string hexify(T const & x)
{
char const alphabet[] = "0123456789ABCDEF";
std::string result(2 * sizeof x, 0);
unsigned char const * const p = reinterpret_cast<unsigned char const *>(&x);
for (std::size_t i = 0; i != sizeof x; ++i)
{
result[2 * i ] = alphabet[p[i] / 16];
result[2 * i + 1] = alphabet[p[i] % 16];
}
return result;
}
模板
std::string hexify(T const&x)
{
字符常量字母[]=“0123456789ABCDEF”;
std::字符串结果(2*sizeof x,0);
无符号字符常量*常量p=重新解释强制转换(&x);
对于(std::size\u t i=0;i!=sizeof x;++i)
{
结果[2*i]=字母表[p[i]/16];
结果[2*i+1]=字母[p[i]%16];
}
返回结果;
}
无符号字符常量*常量p
的含义是什么?它是否等同于常量无符号字符*常量p
?+(初始化字符串时必须添加默认字符)@文森特:啊,是的,忘了默认值。我可能更喜欢reserve
和push_back
。是的,类型是一样的。
template <typename T>
std::string hexify(T const & x)
{
char const alphabet[] = "0123456789ABCDEF";
std::string result(2 * sizeof x, 0);
unsigned char const * const p = reinterpret_cast<unsigned char const *>(&x);
for (std::size_t i = 0; i != sizeof x; ++i)
{
result[2 * i ] = alphabet[p[i] / 16];
result[2 * i + 1] = alphabet[p[i] % 16];
}
return result;
}