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 int
which I'd like to convert to a hex string for later printing.
我可以找到一些方法来实现它,但它们似乎主要是针对C语言的。这是一个非常简单的问题;我有一个整数,我想把它转换成十六进制字符串,以便以后打印。
13 个解决方案
#1
146
Use <iomanip>
's std::hex
. If you print, just send it to std::cout
, if not, then use std::stringstream
使用< iomanip > ' s std::十六进制。如果您打印,只需发送到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 setfill
and setw
this to circumvent the problem:
您可能遇到的一个问题是,这产生了表示它所需的精确数字。您可以使用setfill和setw来绕过这个问题:
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();
}
#2
24
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;
}
#3
19
Use std::stringstream
to 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();
#4
9
Just print it as an hexadecimal number:
把它打印成十六进制数字:
int i = /* ... */;
std::cout << std::hex << i;
#5
6
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;
}
#6
2
int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30
#7
1
For those of you who figured out that many/most of the ios::fmtflags
don't work with std::stringstream
yet like the template idea that Kornel posted way back when, the following works and is relatively clean:
对于那些发现了很多/大部分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);
#8
1
Code for your reference:
代码,供您参考:
#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;
}
#9
0
Just have a look on my solution,[1] that I verbatim copied from my project, so there a German is API doc included. My goal was to combine flexibility and safety within my actual needs:[2]
看看我的解决方案[1],它是从我的项目中逐字复制的,所以包含了一个德语的API doc。我的目标是在我的实际需求中结合灵活性和安全性:[2]
-
no
0x
prefix added: caller may decide - 不添加0x前缀:调用者可以决定
- automatic width deduction: less typing
- 自动宽度演绎:少打字。
- explicit width control: widening for formatting, (lossless) shrinking to save space
- 显式宽度控制:扩展格式,(无损)缩小以节省空间
- capable for dealing with
long long
- 能应付长时间的工作
- restricted to integral types: avoid surprises by silent conversions
- 仅限于整体类型:避免意外的无声转换
- ease of understanding
- 易于理解
- no hard-coded limit
- 没有硬编码的限制
#include <string>
#include <sstream>
#include <iomanip>
/// Vertextet einen Ganzzahlwert val im Hexadezimalformat.
/// Auf die Minimal-Breite width wird mit führenden Nullen aufgefüllt;
/// falls nicht angegeben, wird diese Breite aus dem Typ des Arguments
/// abgeleitet. Funktion geeignet von char bis long long.
/// Zeiger, Fließkommazahlen u.ä. werden nicht unterstützt, ihre
/// Übergabe führt zu einem (beabsichtigten!) Compilerfehler.
/// Grundlagen aus: http://*.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
return ss.str();
}
[1] based on the answer by Kornel Kisielewicz
[2] Translated into the language of CppTest, this is how it reads:
[1]根据考雷特语中Kornel Kisielewicz的回答,如下:
TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
#10
#11
0
Try this:
试试这个:
#include<iostream>
using namespace std;
int main() {
int *a = new int;//or put a number exept new int
//use * for pointer
cin >> *a;
cout << a; //if integer that is made as pointer printed without *, than it will print hex value
return 0;
//I hope i help you
}
#12
0
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_t
values passed) to std::stringstream
are treated as char, which doesn't give you the result you want. Passing such integers to std::to_string
handles 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.
注意:我本想在原答案的注释中添加这个,但我没有代表可以评论。
#13
0
This question is old, but I'm surprised why no one mentioned boost::format
:
这个问题由来已久,但我很奇怪为什么没有人提到boost::格式:
cout << (boost::format("%x") % 1234).str(); // output is: 4d2
#1
146
Use <iomanip>
's std::hex
. If you print, just send it to std::cout
, if not, then use std::stringstream
使用< iomanip > ' s std::十六进制。如果您打印,只需发送到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 setfill
and setw
this to circumvent the problem:
您可能遇到的一个问题是,这产生了表示它所需的精确数字。您可以使用setfill和setw来绕过这个问题:
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();
}
#2
24
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;
}
#3
19
Use std::stringstream
to 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();
#4
9
Just print it as an hexadecimal number:
把它打印成十六进制数字:
int i = /* ... */;
std::cout << std::hex << i;
#5
6
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;
}
#6
2
int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30
#7
1
For those of you who figured out that many/most of the ios::fmtflags
don't work with std::stringstream
yet like the template idea that Kornel posted way back when, the following works and is relatively clean:
对于那些发现了很多/大部分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);
#8
1
Code for your reference:
代码,供您参考:
#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;
}
#9
0
Just have a look on my solution,[1] that I verbatim copied from my project, so there a German is API doc included. My goal was to combine flexibility and safety within my actual needs:[2]
看看我的解决方案[1],它是从我的项目中逐字复制的,所以包含了一个德语的API doc。我的目标是在我的实际需求中结合灵活性和安全性:[2]
-
no
0x
prefix added: caller may decide - 不添加0x前缀:调用者可以决定
- automatic width deduction: less typing
- 自动宽度演绎:少打字。
- explicit width control: widening for formatting, (lossless) shrinking to save space
- 显式宽度控制:扩展格式,(无损)缩小以节省空间
- capable for dealing with
long long
- 能应付长时间的工作
- restricted to integral types: avoid surprises by silent conversions
- 仅限于整体类型:避免意外的无声转换
- ease of understanding
- 易于理解
- no hard-coded limit
- 没有硬编码的限制
#include <string>
#include <sstream>
#include <iomanip>
/// Vertextet einen Ganzzahlwert val im Hexadezimalformat.
/// Auf die Minimal-Breite width wird mit führenden Nullen aufgefüllt;
/// falls nicht angegeben, wird diese Breite aus dem Typ des Arguments
/// abgeleitet. Funktion geeignet von char bis long long.
/// Zeiger, Fließkommazahlen u.ä. werden nicht unterstützt, ihre
/// Übergabe führt zu einem (beabsichtigten!) Compilerfehler.
/// Grundlagen aus: http://*.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
return ss.str();
}
[1] based on the answer by Kornel Kisielewicz
[2] Translated into the language of CppTest, this is how it reads:
[1]根据考雷特语中Kornel Kisielewicz的回答,如下:
TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
#10
0
I do:
我做的事:
int hex = 10;
std::string hexstring = stringFormat("%X", hex);
Take a look at SO answer from iFreilicht and the required template header-file from here GIST!
看一看iFreilicht的回答和这里要求的模板头文件要点!
#11
0
Try this:
试试这个:
#include<iostream>
using namespace std;
int main() {
int *a = new int;//or put a number exept new int
//use * for pointer
cin >> *a;
cout << a; //if integer that is made as pointer printed without *, than it will print hex value
return 0;
//I hope i help you
}
#12
0
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_t
values passed) to std::stringstream
are treated as char, which doesn't give you the result you want. Passing such integers to std::to_string
handles 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.
注意:我本想在原答案的注释中添加这个,但我没有代表可以评论。
#13
0
This question is old, but I'm surprised why no one mentioned boost::format
:
这个问题由来已久,但我很奇怪为什么没有人提到boost::格式:
cout << (boost::format("%x") % 1234).str(); // output is: 4d2