Skip to content

Commit f3d021b

Browse files
authored
Merge pull request #289 from boostorg/integer
Fix `to_chars` of negative 128-bit integers whose absolute value is < 2^64
2 parents 306ae6b + f3f60d2 commit f3d021b

File tree

3 files changed

+62
-1
lines changed

3 files changed

+62
-1
lines changed

include/boost/charconv/detail/to_chars_integer_impl.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -270,7 +270,7 @@ BOOST_CHARCONV_CONSTEXPR to_chars_result to_chars_128integer_impl(char* first, c
270270
// If the value fits into 64 bits use the other method of processing
271271
if (converted_value < (std::numeric_limits<std::uint64_t>::max)())
272272
{
273-
return to_chars_integer_impl(first, last, static_cast<std::uint64_t>(value));
273+
return to_chars_integer_impl(first, last, static_cast<std::uint64_t>(converted_value));
274274
}
275275

276276
constexpr std::uint32_t ten_9 = UINT32_C(1000000000);

test/Jamfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,4 @@ run github_issue_266.cpp ;
7474
run github_issue_267.cpp ;
7575
run github_issue_280.cpp ;
7676
run github_issue_282.cpp ;
77+
run github_issue_int128_320.cpp ;

test/github_issue_int128_320.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright 2026 Matt Borland
2+
// Distributed under the Boost Software License, Version 1.0.
3+
// https://www.boost.org/LICENSE_1_0.txt
4+
//
5+
// See: https://github.com/cppalliance/int128/issues/320
6+
7+
#include <boost/charconv.hpp>
8+
9+
#ifdef BOOST_CHARCONV_HAS_INT128
10+
11+
#if defined(__GNUC__) && __GNUC__ == 12
12+
# pragma GCC diagnostic push
13+
# pragma GCC diagnostic ignored "-Wstringop-overflow"
14+
#endif
15+
16+
#include <boost/core/lightweight_test.hpp>
17+
#include <string>
18+
#include <cstdlib>
19+
20+
void toChars(char* ptr, char* ptrEnd, boost::int128_type i128)
21+
{
22+
auto r = boost::charconv::to_chars(ptr, ptrEnd, i128);
23+
*r.ptr = '\0';
24+
}
25+
26+
void toChars(char* ptr, char* ptrEnd, boost::uint128_type u128)
27+
{
28+
auto r = boost::charconv::to_chars(ptr, ptrEnd, u128);
29+
*r.ptr = '\0';
30+
}
31+
32+
int main()
33+
{
34+
boost::int128_type i128 = -123;
35+
boost::uint128_type u128 = 123;
36+
37+
std::int64_t ref_value = -123;
38+
39+
for (int i = 1; i < 5; ++i)
40+
{
41+
i128 *= i;
42+
u128 *= static_cast<unsigned>(i);
43+
ref_value *= i;
44+
45+
char buf[64] = {};
46+
toChars(buf, buf + 64, i128);
47+
BOOST_TEST_CSTR_EQ(buf, std::to_string(ref_value).c_str());
48+
49+
toChars(buf, buf + 64, u128);
50+
BOOST_TEST_CSTR_EQ(buf, std::to_string(std::abs(ref_value)).c_str());
51+
};
52+
53+
return boost::report_errors();
54+
}
55+
56+
#else
57+
58+
int main() { return 0; }
59+
60+
#endif

0 commit comments

Comments
 (0)