这篇文章将讨论如何在 C++ 中将整数转换为十六进制字符串。
1.使用 std::ostringstream
在 C++ 中将整数转换为十六进制字符串的简单解决方案是使用 std::hex
机械手 std::ostringstream
.这将需要 <sstream>
标题。下面的程序演示了它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <sstream> int main() { int i = 1000; std::ostringstream ss; ss << std::hex << i; std::string result = ss.str(); std::cout << result << std::endl; // 3e8 return 0; } |
在十六进制字符串前面加上基数说明符 0x
,喜欢:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <sstream> int main() { int i = 1000; std::ostringstream ss; ss << "0x" << std::hex << i; std::string result = ss.str(); std::cout << result << std::endl; // 0x3e8 return 0; } |
我们可以进一步使用所需长度的前导零填充十六进制字符串 std::setfill
和 std::setw
函数来自 <iomanip>
标题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <sstream> #include <iomanip> int main() { int i = 1000; std::ostringstream ss; ss << "0x" << std::setfill('0') << std::setw(8) << std::hex << i; std::string result = ss.str(); std::cout << result << std::endl; // 0x000003e8 return 0; } |
2.使用 std::format
从 C++20 开始,推荐的选项是使用 格式化库 用于将整数转换为十六进制字符串。它包含 std::format
作用于 <format>
标头,可以按如下方式使用:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <format> int main() { int i = 1000; std::cout << std::format("{:#x}", i) << std::endl; // 0x3e8 std::cout << std::format("{:#08x}", i) << std::endl; // 0x000003e8 return 0; } |
这 std::format
是基于 {fmt}
图书馆。在 C++20 之前,我们可以使用 {fmt}
库来实现相同的。
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <fmt/format.h> int main() { int i = 1000; std::cout << fmt::format("{:#x}", i) << std::endl; // 0x000003e8 std::cout << fmt::format("{:#08x}", i) << std::endl; // 0x000003e8 return 0; } |
如果 boost 库可用,请尝试使用格式类 boost::format
,其定义在 <boost/format.hpp>
.它提供类似 printf 的格式,如下所示:
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <boost/format.hpp> int main() { int i = 1000; std::cout << (boost::format("%x") % i).str(); // 3e8 return 0; } |
这就是在 C++ 中将整数转换为十六进制字符串。