簡體   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