C ++中的整数到十六进制字符串 [英] Integer to hex string in C++

查看:129
本文介绍了C ++中的整数到十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C ++ 中将整数转换为十六进位字串?

How do I convert an integer to a hex string in C++?

我可以找到一些方法来做,但他们大多看起来是针对C。似乎没有一个本机的方式来做它在C + +。这是一个很简单的问题;我有一个int,我想转换为十六进制字符串以供以后打印。

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 int which I'd like to convert to a hex string for later printing.

推荐答案

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

这篇关于C ++中的整数到十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆