[英]Converting std::string to uint32_t
I have a string like below:我有一个像下面这样的字符串:
std::string strl="ffffffffffffffffffffffffffffffffffffffffffff";
I want to convert it into uint32_t variable like below:我想将其转换为 uint32_t 变量,如下所示:
uint32_t val = std::stoul(strl, nullptr, 16);
The above operation gives a "SIGABRT" signal and gives error:上述操作给出了“SIGABRT”信号并给出错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoul.
What changes to be done for resolving the issue or it is not possible with uint32_t datatype to store the string.为解决问题要进行哪些更改或无法使用 uint32_t 数据类型存储字符串。
uint32_t
can only store up to 0xffffffff
as it's a 32 bit unsigned
type, so it's not possible to store your string with that data type. uint32_t
最多只能存储0xffffffff
因为它是 32 位unsigned
类型,因此无法使用该数据类型存储字符串。
For the string you present, you'll need a big integer library to parse it.对于您提供的字符串,您需要一个大的整数库来解析它。
Boost has a good one, and even includes typedef
s like uint1024_t
, so it's very simple to use. Boost 有一个很好的,甚至包括像uint1024_t
这样的typedef
,所以使用起来非常简单。
See http://www.boost.org/doc/libs/1_58_0/libs/multiprecision/doc/html/index.html请参阅http://www.boost.org/doc/libs/1_58_0/libs/multiprecision/doc/html/index.html
If you really want to store the number in a uint32_t, you'll need to validate it.如果您真的想将数字存储在 uint32_t 中,则需要对其进行验证。
I would approach it something like this:我会像这样接近它:
#include <string>
#include <cstdint>
#include <stdexcept>
#include <iostream>
auto parse_hex_uint32(std::string const& input) -> std::uint32_t
try
{
std::size_t read_len = 0;
auto initial_result = std::stoull(input, &read_len, 16);
if (read_len != input.size())
{
throw std::runtime_error("invalid input: " + input);
}
if (initial_result > std::numeric_limits<std::uint32_t>::max())
{
throw std::out_of_range("number too large: " + std::to_string(initial_result));
}
return std::uint32_t(initial_result);
}
catch(...)
{
std::throw_with_nested(std::runtime_error("failed to parse " + input + " as hex uint32"));
}
void print_exception(const std::exception& e, int level = 0)
{
std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n';
try {
std::rethrow_if_nested(e);
} catch(const std::exception& e) {
print_exception(e, level+1);
} catch(...) {}
}
int main()
{
using namespace std::literals;
auto input = "ffffffffffffffff"s;
try
{
std::cout << parse_hex_uint32(input) << std::endl;
return 0;
}
catch(std::exception& e)
{
print_exception(e);
return 100;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.