C++ 中的整数到十六进制字符串
如何在 C++ 中将整数转换为十六进制字符串?
我可以找到一些方法来做到这一点,但它们似乎主要针对 C。似乎没有一种本地方法可以在 C++ 中做到这一点。但这是一个非常简单的问题;我有一个 int
,我想将其转换为十六进制字符串以供以后打印。
How do I convert an integer to a hex string in 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
使用
的std: :十六进制
。如果打印,只需将其发送到std::cout
,如果没有,则使用std::stringstream
您可以在第一个
<<
前面加上<< “0x”
或任何您喜欢的内容(如果您愿意)。其他感兴趣的操作是 std::oct(八进制)和 std::dec(返回十进制)。
您可能会遇到的一个问题是,这会产生表示它所需的精确位数。您可以使用
setfill
和setw
这来规避这个问题:所以最后,我建议这样一个函数:
Use
<iomanip>
'sstd::hex
. If you print, just send it tostd::cout
, if not, then usestd::stringstream
You can prepend the first
<<
with<< "0x"
or whatever you like if you wish.Other manips of interest are
std::oct
(octal) andstd::dec
(back to decimal).One problem you may encounter is the fact that this produces the exact amount of digits needed to represent it. You may use
setfill
andsetw
this to circumvent the problem:So finally, I'd suggest such a function:
您可以使用 C++20
std::format
:在
std::format
广泛使用之前,您可以使用{fmt } 库,std::format
基于 (godbolt ):免责声明:我是 {fmt} 和 C++20
std::format
的作者。You can do it with C++20
std::format
:Until
std::format
is widely available you can use the {fmt} library,std::format
is based on (godbolt):Disclaimer: I'm the author of {fmt} and C++20
std::format
.为了使其更轻更快,我建议使用直接填充字符串。
To make it lighter and faster I suggest to use direct filling of a string.
使用 std::stringstream 将整数转换为字符串及其特殊操纵器来设置基数。例如这样:
Use
std::stringstream
to convert integers into strings and its special manipulators to set the base. For example like that:只需将其打印为十六进制数:
Just print it as an hexadecimal number:
从 C++20 开始,使用
std::format
< /a>,你可以这样做:演示
Since C++20, with
std::format
, you might do:Demo
一种新的 C++17 方式:来自
的std::to_chars
(https://en.cppreference.com/w/cpp/utility/to_chars):这有点冗长,因为
std::to_chars
使用预分配的缓冲区来避免动态分配,但这也可以让您优化代码,因为如果处于热点,分配会变得非常昂贵。对于额外的优化,您可以省略预初始化缓冲区并检查 to_chars 的返回值以检查错误并获取写入数据的长度。注意:
to_chars
不写入空终止符!A new C++17 way:
std::to_chars
from<charconv>
(https://en.cppreference.com/w/cpp/utility/to_chars):This is a bit verbose since
std::to_chars
works with a pre-allocated buffer to avoid dynamic allocations, but this also lets you optimize the code since allocations get very expensive if this is in a hot spot.For extra optimization, you can omit pre-initializing the buffer and check the return value of
to_chars
to check for errors and get the length of the data written. Note:to_chars
does NOT write a null-terminator!您可以尝试以下操作。它正在工作...
You can try the following. It's working...
只需查看我从项目中逐字复制的解决方案[1]即可。我的目标是在实际需求中结合灵活性和安全性:[3]
0x
前缀:调用者可以决定long long
[1]基于科内尔·基西莱维奇
[2] 仅将德语 API 文档翻译为英语。
[3] 翻译成CppTest的语言,是这样的:
Just have a look on my solution,[1] that I verbatim[2] copied from my project. My goal was to combine flexibility and safety within my actual needs:[3]
0x
prefix added: caller may decidelong long
[1] based on the answer by Kornel Kisielewicz
[2] Only the German API doc was translated to English.
[3] Translated into the language of CppTest, this is how it reads:
我可以看到其他人用作答案的所有精心设计的编码示例,但是在 C++ 应用程序中简单地使用它并没有什么问题:
for num = 128:
https://en.wikipedia.org/wiki/Printf_format_string
C++ 实际上是经过扩展的原始 C 语言,因此 C 中的任何内容也是完全有效的 C++。
I can see all the elaborate coding samples others have used as answers, but there is nothing wrong with simply having this in a C++ application:
for num = 128:
https://en.wikipedia.org/wiki/Printf_format_string
C++ is effectively the original C language which has been extended, so anything in C is also perfectly valid C++.
感谢下面林肯的评论,我更改了这个答案。
以下答案在编译时正确处理 8 位整数。然而,它确实需要 C++17。如果您没有 C++17,则必须执行其他操作(例如,提供此函数的重载,一个用于 uint8_t,一个用于 int8_t,或者使用除“if constexpr”之外的其他内容,可能是enable_if)。
原始答案没有像我想象的那样正确处理 8 位整数:
Kornel Kisielewicz 的答案很棒。但是,稍微添加一点有助于捕获使用没有意义的模板参数(例如浮点数)调用此函数或会导致混乱的编译器错误(例如用户定义类型)的情况。
我编辑了此内容以添加对 std::to_string 的调用,因为将处理
std::stringstream
的 8 位整数类型(例如传递的std::uint8_t
值)作为 char,它不会给你你想要的结果。将此类整数传递给 std::to_string 可以正确处理它们,并且在使用其他更大的整数类型时不会造成任何损害。当然,在这些情况下,您可能会遭受轻微的性能影响,因为 std::to_string 调用是不必要的。注意:我只是将其添加到原始答案的评论中,但我没有代表发表评论。
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).
Original answer that doesn't handle 8-bit ints correctly as I thought it did:
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).
I've edited this to add a call to std::to_string because 8-bit integer types (e.g.
std::uint8_t
values passed) tostd::stringstream
are treated as char, which doesn't give you the result you want. Passing such integers tostd::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.Note: I would have just added this in a comment to the original answer, but I don't have the rep to comment.
_itoa_s
swprintf_s
_itoa_s
swprintf_s
我的解决方案。仅允许整数类型。
您可以在 https://replit.com/@JomaCorpFX/ToHex
上测试/运行更新。您可以在第二个参数中设置可选前缀 0x。
definition.h
main.cpp
结果:
My solution. Only integral types are allowed.
You can test/run on https://replit.com/@JomaCorpFX/ToHex
Update. You can set optional prefix 0x in second parameter.
definition.h
main.cpp
Results:
另一种简单的方法
ANOTHER SIMPLE APPROACH
对于那些发现许多/大多数
ios::fmtflags
不能与std::stringstream
一起使用但喜欢 Kornel 早前发布的模板想法的人当,以下工作有效并且相对干净:For those of you who figured out that many/most of the
ios::fmtflags
don't work withstd::stringstream
yet like the template idea that Kornel posted way back when, the following works and is relatively clean:我这样做:
看看来自 iFreilicht 的 SO 答案以及此处所需的模板头文件GIST!
I do:
Take a look at SO answer from iFreilicht and the required template header-file from here GIST!
代码供您参考:
Code for your reference:
我想补充一个答案来欣赏C++语言的美妙。其对高水平和低水平工作的适应性。快乐的编程。
示例:
I would like to add an answer to enjoy the beauty of C ++ language. Its adaptability to work at high and low levels. Happy programming.
Examples:
对于固定位数,例如 2:
您还可以编写一个 for 循环变体来处理可变位数
优点:
for fixed number of digits, for instance 2:
you can also write a for cycle variant to handle variable digits amount
benefits:
char_to_hex 返回两个字符的字符串
char_to_hex returns a string of two characters
使用变量:
then:
将导致
selA
包含字符串SELA;0x55;
请注意,
55
周围的内容只是与我的应用程序中使用的串行协议。With the variable:
then:
will result in
selA
containing the stringSELA;0x55;
Note that the things surrounding the
55
are just particulars related to the serial protocol used in my application.使用 void 指针:
添加 0x:
输出:
Using void pointer:
Adding 0x:
Outputs:
这个问题很老了,但我认为给出的答案并不是最好的。
如果您使用的是 C++20,那么您可以选择使用 std::format,这是一个非常好的解决方案。但是,如果您使用的是 C++11/14/17 或更低版本,则不会有此选项。
大多数其他答案要么使用 std::stringstream 要么自己实现自己的转换,直接修改底层字符串缓冲区。
第一个选项重量相当重。第二种选择本质上是不安全且容易出现错误的。
由于最近我必须实现一个整数到十六进制字符串,所以我选择使用函数重载和模板部分特化来实现真正的 C++ 安全实现,让编译器处理类型检查。该代码使用
sprintf
(它的风格之一通常由std::to_string
标准库使用)。它依赖于模板部分特化来正确选择正确的 sprintf 格式和前导 0 加法。它单独并正确地处理不同操作系统和体系结构的不同指针大小和unsigned long
大小。 (4/4/4、4/4/8、4/8/8)此答案针对 C++11
H 文件:
CPP 文件
This question is quite old but the answers given are to my opinion not the best.
If you are using C++20 then you have the option to use
std::format
which is a very good solution. However if you are using C++11/14/17 or below you will not have this option.Most other answers either use the
std::stringstream
or implement their own conversion modifying the underlying string buffer directly by themselves.The first option is rather heavy weight. The second option is inherently insecure and bug prone.
Since I had to implement an integer to hex string lately I chose to do a a true C++ safe implementation using function overloads and template partial specialization to let the compiler handle the type checks. The code uses
sprintf
(which one of its flavors is generally used by the standard library forstd::to_string
). And it relies on template partial specialization to correctly select the rightsprintf
format and leading 0 addition. It separately and correctly handles different pointer sizes andunsigned long
sizes for different OSs and architectures. (4/4/4, 4/4/8, 4/8/8)This answer targets C++11
H File:
CPP File
我读到的所有答案都非常慢,除了其中一个,但那个答案仅适用于小端 CPU。这是一个适用于大端和小端 CPU 的快速实现。
与
std::format
和fmt::format("{:x}", value)
相比,我得到的值在 2x 之间(对于值 > (1ll << ; 60)) 和 6 倍速度(对于较小的值)。输入/输出示例:
All the answers I read are pretty slow, except one of them, but that one only works for little endian CPUs. Here's a fast implementation that works on big and little endian CPUs.
Compared to
std::format
andfmt::format("{:x}", value)
, I get between 2x (for values > (1ll << 60)) and 6x the speed (for smaller values).Examples of input/output:
要将整数转换为 C++ 17 中的十六进制字符串,您可以使用
std::stringstream
使用以下代码:在此我们还处理负值的 egde 情况我创建了方法来访问它以方便使用。
To convert an integer to a Hex string in C++ 17, you can use the following code using
std::stringstream
:In this we also handle egde cases for negative values as well and i created method for this to access for ease of use.
您可以使用此模板函数
可以用不同的整数来调用它,例如:
IntToHexForm(10)
将返回 00000010IntToHexForm((unsigned char)10)
将返回 10You can use this template function
You can call it with different integers, for example:
IntToHexForm(10)
will return 00000010IntToHexForm((unsigned char)10)
will return 10