JsonCpp 不能防止 uint64 溢出并且有奇怪的行为

问题描述 投票:0回答:1

我正在使用 JsonCpp,并注意到在到达 uint64 范围末尾时出现奇怪的行为。

范围内的数字工作正常。 超出范围但在

[2**64,2**64+2**10]
之间的数字返回 0。
2**64+2**10
上方的数字会引发异常。

这是预期的吗?我可以配置 JsonCpp 来为我执行这些验证吗?

提前致谢!

下面是演示该问题的代码片段。

#include <iostream>
#include <jsoncpp/json/json.h>
#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/value.h>


int main() {
    //std::string uint64Str = "1234"; // any number in range [0, 2**64-1] works correctly (prints uint64Str)
    //std::string uint64Str = "18446744073709551615"; // any number in range [0, 2**64-1] works correctly, including 2**64-1 (prints uint64Str)
    //std::string uint64Str = "18446744073709551616"; //max uint64 + 1 print 0
    //std::string uint64Str = "18446744073709551617"; //max uint64 + 2 print 0
    // ...
    //std::string uint64Str = "18446744073709553663"; //max uint64 + 2048 print 0
    //std::string uint64Str = "18446744073709553664"; //max uint64 + 2049 print 0
    std::string uint64Str = "18446744073709553665"; //max uint64 + 2050 (or more) throws instance of 'Json::LogicError' what():  double out of UInt64 range
    Json::Value root;
    Json::Reader reader;
    bool parsingResult = reader.parse("{\"key\":"+uint64Str+"}", root);
        std::cout<<root["key"].asUInt64()<<std::endl;
    
        return 0;
}

c++ integer-overflow jsoncpp
1个回答
0
投票

问题在于非常大的数字被存储为real(它不适合

uint64_t
)。您也需要将其视为real

std::cout << root["key"].asDouble() << std::endl;
//                       ^^^^^^^^^^
© www.soinside.com 2019 - 2024. All rights reserved.