Skip to content

Commit 660511c

Browse files
committed
Update Convert.cpp
1 parent 9bebff8 commit 660511c

File tree

1 file changed

+24
-8
lines changed

1 file changed

+24
-8
lines changed

src/Convert.cpp

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,38 @@ void fromNonZeroT(T val, std::string& out)
1717
{
1818
// Ensure the template type T is an integral type
1919
static_assert(std::is_integral_v<T>, "T must be an integral type");
20+
using U = std::make_unsigned_t<T>;
21+
2022
constexpr std::size_t MaxDigits = OpenShock::Util::Digits10CountMax<T>;
2123

2224
char buf[MaxDigits];
2325

2426
// Start from the end of the buffer to construct the number in reverse (from least to most significant digit)
25-
char* ptr = buf + MaxDigits;
27+
char* const end = buf + MaxDigits;
28+
char* ptr = end;
2629

27-
bool negative = val < 0;
28-
if (negative) {
29-
val = -val; // Make the value positive for digit extraction
30+
U u;
31+
bool negative = false;
32+
33+
if constexpr (std::is_signed_v<T>) {
34+
if (val < 0) {
35+
negative = true;
36+
37+
// Convert to unsigned, then take the modular negation.
38+
// This is well-defined and yields the magnitude of val.
39+
u = U(0) - U(val);
40+
} else {
41+
u = U(val);
42+
}
43+
} else {
44+
// Unsigned types: just use the value as-is.
45+
u = U(val);
3046
}
3147

3248
// Extract digits and store them in reverse order in the buffer
33-
while (val > 0) {
34-
*--ptr = '0' + (val % 10);
35-
val /= 10;
49+
while (u > 0) {
50+
*--ptr = char('0' + (u % 10));
51+
u /= 10;
3652
}
3753

3854
// If the number was negative, add the negative sign
@@ -41,7 +57,7 @@ void fromNonZeroT(T val, std::string& out)
4157
}
4258

4359
// Append the resulting string to the output
44-
out.append(ptr, buf + MaxDigits);
60+
out.append(ptr, end - ptr);
4561
}
4662

4763
// Base converter

0 commit comments

Comments
 (0)