C++将字符串转换为十六进制,反之亦然
在 C++ 中将字符串转换为十六进制或反之亦然的最佳方法是什么?
示例:
- 将
"Hello World"
等字符串转换为十六进制格式:48656C6C6F20576F726C64
- 并从十六进制
48656C6C6F20576F726C64
转换为字符串:"Hello World"< /代码>
What is the best way to convert a string to hex and vice versa in C++?
Example:
- A string like
"Hello World"
to hex format:48656C6C6F20576F726C64
- And from hex
48656C6C6F20576F726C64
to string:"Hello World"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
啊,给你:(
这里假设一个 char 有 8 位,所以它不是很便携,但你可以从这里获取它。)
Ah, here you go:
(This assumes that a char has 8 bits, so it's not very portable, but you can take it from here.)
使用查找表之类的方法是可行的,但有点矫枉过正,这里有一些非常简单的方法,可以将字符串转换为十六进制,然后将十六进制转换回字符串:
Using lookup tables and the like works, but is just overkill, here are some very simple ways of taking a string to hex and hex back to a string:
我认为有一个更简单、更优雅的解决方案。在某些情况下,上述一些方法甚至可能会抛出未处理的异常。这是一个万无一失(永远不会出错)且非常快的代码。只需尝试一下,并比较速度和紧凑性方面的结果:
测试代码:
和结果是:
I think there is a much simpler and more elegant solution. Some of the above-mentioned methods may even throw unhandled exceptions in some cases. Here is a fool-proof (as in never goes wrong) and very fast code. Just try it and compare the results in terms of speed and compactness:
Test the code:
and the result is:
从 C++17 开始,还有 std::from_chars。以下函数接受十六进制字符的字符串并返回 T 的向量:
As of C++17 there's also std::from_chars. The following function takes a string of hex characters and returns a vector of T:
你可以试试这个。它正在工作...
You can try this. It's Working...
使用标准库的最简单示例。
要检查输出,codepad 返回:6e
和在线 ascii 到十六进制转换工具 也产生 6e。所以它有效。
您还可以这样做:
Simplest example using the Standard Library.
To check the output, codepad returns: 6e
and an online ascii-to-hexadecimal conversion tool yields 6e as well. So it works.
You can also do this:
这有点快:
This is a bit faster:
这是另一种解决方案,很大程度上受到@fredoverflow 的解决方案的启发。
长度是预期用途中必需的参数。
Here is an other solution, largely inspired by the one by @fredoverflow.
Length was required parameter in the intended usage.
这会将“Hello World”转换为“48656c6c6f20576f726c64”,并将该十六进制值存储在 str1 中,并将“48656c6c6f20576f726c64”转换为“Hello World”。
This will convert "Hello World" to "48656c6c6f20576f726c64" and will store this hex value in str1 and also will convert "48656c6c6f20576f726c64" to "Hello World".
https://www.boost.org/doc/libs/ 1_78_0/boost/algorithm/hex.hpp
https://www.boost.org/doc/libs/1_78_0/boost/algorithm/hex.hpp
这适用于打印 UTF-8 编码的字符串(长度可变)
小测试
输出:
查看如何 UTF-8 字符
ñ
使用更多字节进行编码。This works for printing UTF-8 encoded strings (which are variable in length)
Little test
The output:
See how UTF-8 characters
ñ
are encoded using more bytes.为什么没有人使用 sprintf?
Why has nobody used sprintf?