繁体   English   中英

将 std::string 转换为 uint32_t

[英]Converting std::string to uint32_t

我有一个像下面这样的字符串:

std::string strl="ffffffffffffffffffffffffffffffffffffffffffff";

我想将其转换为 uint32_t 变量,如下所示:

uint32_t val = std::stoul(strl, nullptr, 16);

上述操作给出了“SIGABRT”信号并给出错误:

terminate called after throwing an instance of 'std::out_of_range'
what():  stoul.

为解决问题要进行哪些更改或无法使用 uint32_t 数据类型存储字符串。

uint32_t最多只能存储0xffffffff因为它是 32 位unsigned类型,因此无法使用该数据类型存储字符串。

对于您提供的字符串,您需要一个大的整数库来解析它。

Boost 有一个很好的,甚至包括像uint1024_t这样的typedef ,所以使用起来非常简单。

请参阅http://www.boost.org/doc/libs/1_58_0/libs/multiprecision/doc/html/index.html

如果您真的想将数字存储在 uint32_t 中,则需要对其进行验证。

我会像这样接近它:

#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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM