C ++中的整数到十六进制字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5100718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Integer to hex string in C++
提问by kryptobs2000
How do I convert an integer to a hex string in C++?
如何在C++中将整数转换为十六进制字符串?
I can find some ways to do it, but they mostly seem targeted towards C. It doesn't seem there's a native way to do it in C++. It is a pretty simple problem though; I've got an intwhich I'd like to convert to a hex string for later printing.
我可以找到一些方法来做到这一点,但它们似乎主要针对 C。在 C++ 中似乎没有一种本地方法可以做到这一点。不过,这是一个非常简单的问题;我有一个int我想转换为十六进制字符串以供以后打印。
回答by Kornel Kisielewicz
Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream
使用<iomanip>的 std::hex。如果您打印,只需将其发送到std::cout,如果没有,则使用std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
You can prepend the first <<with << "0x"or whatever you like if you wish.
你可以在前面加上第一<<用<< "0x"或任何你喜欢的,如果你想。
Other manips of interest are std::oct(octal) and std::dec(back to decimal).
其他感兴趣的操作是std::oct(八进制)和std::dec(回到十进制)。
One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfilland setwthis to circumvent the problem:
您可能会遇到的一个问题是,这会产生表示它所需的确切数字量。您可以使用setfilland setwthis 来规避问题:
stream << std::setfill ('0') << std::setw(sizeof(your_type)*2)
<< std::hex << your_int;
So finally, I'd suggest such a function:
所以最后,我建议这样一个功能:
template< typename T >
std::string int_to_hex( T i )
{
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
return stream.str();
}
回答by AndreyS Scherbakov
To make it lighter and faster I suggest to use direct filling of a string.
为了使它更轻更快,我建议使用直接填充字符串。
template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I)<<1) {
static const char* digits = "0123456789ABCDEF";
std::string rc(hex_len,'0');
for (size_t i=0, j=(hex_len-1)*4 ; i<hex_len; ++i,j-=4)
rc[i] = digits[(w>>j) & 0x0f];
return rc;
}
回答by phlipsy
Use std::stringstreamto convert integers into strings and its special manipulators to set the base. For example like that:
使用std::stringstream转换成整数的字符串和其特殊的操纵器设置的基础。例如像这样:
std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();
回答by Etienne de Martel
Just print it as an hexadecimal number:
只需将其打印为十六进制数:
int i = /* ... */;
std::cout << std::hex << i;
回答by Mahmut EFE
You can try the following. It's working...
您可以尝试以下操作。它的工作...
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
{
ostringstream oss;
oss << f << t;
return oss.str();
}
int main ()
{
cout<<to_string<long>(123456, hex)<<endl;
system("PAUSE");
return 0;
}
回答by s4eed
This question is old, but I'm surprised why no one mentioned boost::format:
这个问题很老了,但我很惊讶为什么没有人提到boost::format:
cout << (boost::format("%x") % 1234).str(); // output is: 4d2
回答by Loss Mentality
Thanks to Lincoln's comment below, I've changed this answer.
感谢林肯在下面的评论,我改变了这个答案。
The following answer properly handles 8-bit ints at compile time. It doees, however, require C++17. If you don't have C++17, you'll have to do something else (e.g. provide overloads of this function, one for uint8_t and one for int8_t, or use something besides "if constexpr", maybe enable_if).
以下答案在编译时正确处理 8 位整数。但是,它确实需要 C++17。如果您没有 C++17,您将不得不做其他事情(例如,提供此函数的重载,一个用于 uint8_t,另一个用于 int8_t,或者使用除“if constexpr”之外的其他内容,可能是 enable_if)。
template< typename T >
std::string int_to_hex( T i )
{
// Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");
std::stringstream stream;
stream << "0x" << std::setfill ('0') << std::setw(sizeof(T)*2) << std::hex;
// If T is an 8-bit integer type (e.g. uint8_t or int8_t) it will be
// treated as an ASCII code, giving the wrong result. So we use C++17's
// "if constexpr" to have the compiler decides at compile-time if it's
// converting an 8-bit int or not.
if constexpr (std::is_same_v<std::uint8_t, T>)
{
// Unsigned 8-bit unsigned int type. Cast to int (thanks Lincoln) to
// avoid ASCII code interpretation of the int. The number of hex digits
// in the returned string will still be two, which is correct for 8 bits,
// because of the 'sizeof(T)' above.
stream << static_cast<int>(i);
}
else if (std::is_same_v<std::int8_t, T>)
{
// For 8-bit signed int, same as above, except we must first cast to unsigned
// int, because values above 127d (0x7f) in the int will cause further issues.
// if we cast directly to int.
stream << static_cast<int>(static_cast<uint8_t>(i));
}
else
{
// No cast needed for ints wider than 8 bits.
stream << i;
}
return stream.str();
}
Original answer that doesn't handle 8-bit ints correctly as I thought it did:
没有像我认为的那样正确处理 8 位整数的原始答案:
Kornel Kisielewicz's answer is great. But a slight addition helps catch cases where you're calling this function with template arguments that don't make sense (e.g. float) or that would result in messy compiler errors (e.g. user-defined type).
Kornel Kisielewicz 的回答很棒。但是稍加添加有助于捕获您使用模板参数调用此函数的情况,这些参数没有意义(例如 float)或者会导致混乱的编译器错误(例如用户定义的类型)。
template< typename T >
std::string int_to_hex( T i )
{
// Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");
std::stringstream stream;
stream << "0x"
<< std::setfill ('0') << std::setw(sizeof(T)*2)
<< std::hex << i;
// Optional: replace above line with this to handle 8-bit integers.
// << std::hex << std::to_string(i);
return stream.str();
}
I've edited this to add a call to std::to_string because 8-bit integer types (e.g. std::uint8_tvalues passed) to std::stringstreamare treated as char, which doesn't give you the result you want. Passing such integers to std::to_stringhandles them correctly and doesn't hurt things when using other, larger integer types. Of course you may possibly suffer a slight performance hit in these cases since the std::to_string call is unnecessary.
我编辑了它以添加对 std::to_string 的调用,因为 8 位整数类型(例如std::uint8_t传递的值)std::stringstream被视为 char,它不会给你想要的结果。传递这些整数以std::to_string正确处理它们,并且在使用其他更大的整数类型时不会造成伤害。当然,在这些情况下您可能会遭受轻微的性能损失,因为 std::to_string 调用是不必要的。
Note: I would have just added this in a comment to the original answer, but I don't have the rep to comment.
注意:我会在原始答案的评论中添加这个,但我没有代表评论。
回答by Mahesh
int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30
回答by Kevin
For those of you who figured out that many/most of the ios::fmtflagsdon't work with std::stringstreamyet like the template idea that Kornel posted way back when, the following works and is relatively clean:
对于那些你们谁想通了,许多/大多数的ios::fmtflags做不工作std::stringstream但像模板想法科内尔贴的时候,下面的工作是比较干净的方式回到:
#include <iomanip>
#include <sstream>
template< typename T >
std::string hexify(T i)
{
std::stringbuf buf;
std::ostream os(&buf);
os << "0x" << std::setfill('0') << std::setw(sizeof(T) * 2)
<< std::hex << i;
return buf.str().c_str();
}
int someNumber = 314159265;
std::string hexified = hexify< int >(someNumber);
回答by parasrish
Code for your reference:
代码供您参考:
#include <iomanip>
#include <sstream>
...
string intToHexString(int intValue) {
string hexStr;
/// integer value to hex-string
std::stringstream sstream;
sstream << "0x"
<< std::setfill ('0') << std::setw(2)
<< std::hex << (int)intValue;
hexStr= sstream.str();
sstream.clear(); //clears out the stream-string
return hexStr;
}

