Skip to content

Commit

Permalink
Merge pull request #122 from boostorg/hexadecimal
Browse files Browse the repository at this point in the history
Print float128 as hexadecimal floating point literals if the ios_base…
  • Loading branch information
NAThompson authored Apr 12, 2019
2 parents c062629 + 32628fb commit de3ab81
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
14 changes: 10 additions & 4 deletions include/boost/multiprecision/float128.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,7 @@ struct float128_backend
std::string str(std::streamsize digits, std::ios_base::fmtflags f)const
{
#ifndef BOOST_MP_USE_QUAD
char buf[100];
boost::scoped_array<char> buf2;
char buf[128];
std::string format = "%";
if(f & std::ios_base::showpos)
format += "+";
Expand All @@ -275,18 +274,25 @@ struct float128_backend
if(digits == 0)
digits = 36;
format += "Q";

if(f & std::ios_base::scientific)
format += "e";
else if(f & std::ios_base::fixed)
format += "f";
else
format += "g";

int v = quadmath_snprintf (buf, 100, format.c_str(), digits, m_value);
int v;
if ((f & std::ios_base::scientific) && (f & std::ios_base::fixed) ) {
v = quadmath_snprintf (buf, sizeof buf, "%Qa", m_value);
} else {
v = quadmath_snprintf (buf, sizeof buf, format.c_str(), digits, m_value);
}

if((v < 0) || (v >= 99))
if((v < 0) || (v >= 127))
{
int v_max = v;
boost::scoped_array<char> buf2;
buf2.reset(new char[v+3]);
v = quadmath_snprintf (&buf2[0], v_max + 3, format.c_str(), digits, m_value);
if(v >= v_max + 3)
Expand Down
27 changes: 27 additions & 0 deletions test/test_float_io.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,32 @@ void test_round_trip()
}
}

#ifdef TEST_FLOAT128
void test_hexadecimal_floating_point()
{
using boost::multiprecision::float128;

float128 x = 0x1p+0Q;

std::string s = x.str(0, std::ios_base::fmtflags(std::ios_base::fixed | std::ios_base::scientific));
BOOST_CHECK_EQUAL(s, "0x1p+0");

s = x.str(0, std::ios_base::fmtflags(std::ios_base::floatfield));
BOOST_CHECK_EQUAL(s, "0x1p+0");

x = -1;
s = x.str(0, std::ios_base::fmtflags(std::ios_base::floatfield));
BOOST_CHECK_EQUAL(s, "-0x1p+0");

// hexadecimal representation of pi; test a round trip:
float128 pi1 = 0x1.921fb54442d18469898cc51701b8p+1Q;
s = pi1.str(0, std::ios_base::fmtflags(std::ios_base::floatfield));
float128 pi2(s);
BOOST_CHECK_EQUAL(pi1, pi2);

}
#endif

int main()
{
#ifdef TEST_MPFR_50
Expand Down Expand Up @@ -336,6 +362,7 @@ int main()
#endif
#ifdef TEST_FLOAT128
test<boost::multiprecision::float128>();
test_hexadecimal_floating_point();
#ifndef BOOST_INTEL
test_round_trip<boost::multiprecision::float128>();
#endif
Expand Down

0 comments on commit de3ab81

Please sign in to comment.