且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C ++中的整数到十六进制字符串

更新时间:2023-11-14 23:13:34

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

Use <iomanip>'s std::hex. If you print, just send it to std::cout, if not, then use std::stringstream

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

您可以在第一个<< with <<

You can prepend the first << with << "0x" or whatever you like if you wish.

其他感兴趣的manips是 std :: oct

Other manips of interest are std::oct (octal) and std::dec (back to decimal).

可能遇到的事实是,这产生代表它所需的精确数量的数字。您可以使用 setfill setw 这个来回避问题:

One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use setfill and setw this to circumvent the problem:

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();
}