Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

ieee 754 - How to represent Infinity in floating/double values in C++?

As cppreference says "In IEEE 754, the most common binary representation of floating-point numbers, the positive infinity is the value with all bits of the exponent set and all bits of the fraction cleared.". I tried this code snippet, but I don't see exponent bits set. Am I wrong somewhere?

#include <iostream>
#include <limits>
#include <bitset>
#include <math.h>
using namespace std;
int main() {
    float a = 0b00000000000000000000000000000000;

    double b = std::numeric_limits<double>::infinity();
    bitset<64> x(b);

    cout<<x<<endl;
    return 0;
}

It prints 0000000000000000000000000000000000000000000000000000000000000000 on console.

question from:https://stackoverflow.com/questions/66049285/how-to-represent-infinity-in-floating-double-values-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

std::bitset doesn't have a constructor accepting a double. When you pass double, you instead invoke the constructor that accepts unsigned long long and the double is first implicitly converted to unsigned long long.

Problem is, unsigned long long cannot represent infinity, and the behaviour of the program is consequently undefined. Standard says:

[conv.fpint]

A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.


To see the bits, you can first "bitcast" the floating point to an integer type, and then pass that integer to bitset:

auto int_b = std::bit_cast<std::uint64_t>(b);
std::bitset<64> x(int_b);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...