在C ++中整数转换为hexstring

如何在C ++中将整数转换为hexstring?

我可以find一些方法来做到这一点,但他们似乎主要是针对C.它似乎没有一种原生的方式来在C ++中做到这一点。 这是一个非常简单的问题, 我有一个int,我想要转换为一个hexstring为以后打印。

使用<iomanip>std::hex 。 如果你打印,只要将它发送到std::cout ,如果没有,然后使用std::stringstream

 std::stringstream stream; stream << std::hex << your_int; std::string result( stream.str() ); 

如果你愿意的话,你可以预先安排第一个<< with << "0x"或者任何你喜欢的东西。

其他感兴趣的manip是std::oct (八进制)和std::dec (回到十进制)。

您可能遇到的一个问题是,这会产生表示它所需的确切数量的数字。 你可以使用setfillsetw这个来规避这个问题:

 stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) << std::hex << your_int; 

所以最后,我会build议这样一个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(); } 

使用std::stringstream将整数转换为string,并使用特殊的操纵符来设置基数。 例如那样:

 std::stringstream sstream; sstream << std::hex << my_integer; std::string result = sstream.str(); 

为了使它更轻,更快,我build议使用直接填充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; } 

只需将其打印为hex数字:

 int i = /* ... */; std::cout << std::hex << i; 

你可以尝试以下。 它正在工作…

 #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; } 
 int num = 30; std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30 

对于那些认为很多/大部分的ios::fmtflags不能和std::stringstream一起工作的人来说,就像Kornel发布的模板想法一样,下面的工作是相对干净的:

 #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); 

代码供您参考:

 #include <iomanip> ... 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; }