Skip to content

Unpack float64 get the wrong result. #24

@g199209

Description

@g199209
inline void Unpacker::unpack_type(double &value) {
    if (safe_data() == float64) {
        safe_increment();
        uint64_t data = 0;
        for (auto i = sizeof(uint64_t); i > 0; --i) {
            data += uint64_t(safe_data()) << 8 * (i - 1);
            safe_increment();
        }
        auto bits = std::bitset<64>(data);
        auto mantissa = 1.0;
        for (auto i = 52U; i > 0; --i) {
            if (bits[i - 1]) {
                mantissa += 1.0 / (uint64_t(1) << (53 - i));
            }
        }
        if (bits[63]) {
            mantissa *= -1;
        }
        uint16_t exponent = 0;
        for (auto i = 0U; i < 11; ++i) {
            exponent += bits[i + 52] << i;
        }
        exponent -= 1023;
        value = ldexp(mantissa, exponent);
    } else {
        if (safe_data() == int8 || safe_data() == int16 || safe_data() == int32 || safe_data() == int64) {
            int64_t val = 0;
            unpack_type(val);
            value = float(val);
        } else {
            uint64_t val = 0;
            unpack_type(val);
            value = float(val);
        }
    }
}

If input is zero, ie, all 8 bytes are 0x00, the result should be 0.0. But this code return inf.

Reason:

exponent should be int, rather than uint16_t.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions