diff --git a/include/nlohmann/detail/output/serializer.hpp b/include/nlohmann/detail/output/serializer.hpp index e6811ceb3b..703a69e44c 100644 --- a/include/nlohmann/detail/output/serializer.hpp +++ b/include/nlohmann/detail/output/serializer.hpp @@ -630,7 +630,7 @@ class serializer if (is_negative) { *buffer_ptr = '-'; - abs_value = static_cast(std::abs(static_cast(x))); + abs_value = remove_sign(x); // account one more byte for the minus sign n_chars = 1 + count_digits(abs_value); @@ -811,6 +811,17 @@ class serializer return state; } + inline number_unsigned_t remove_sign(number_unsigned_t x) noexcept + { + return x; + } + + inline number_unsigned_t remove_sign(number_integer_t x) noexcept + { + assert(x < std::numeric_limits::max()); + return static_cast(-(x + 1)) + 1; + } + private: /// the output of the serializer output_adapter_t o = nullptr; diff --git a/single_include/nlohmann/json.hpp b/single_include/nlohmann/json.hpp index 2a32a82963..ae0d5fd5b0 100644 --- a/single_include/nlohmann/json.hpp +++ b/single_include/nlohmann/json.hpp @@ -14264,7 +14264,7 @@ class serializer if (is_negative) { *buffer_ptr = '-'; - abs_value = static_cast(std::abs(static_cast(x))); + abs_value = remove_sign(x); // account one more byte for the minus sign n_chars = 1 + count_digits(abs_value); @@ -14445,6 +14445,17 @@ class serializer return state; } + inline number_unsigned_t remove_sign(number_unsigned_t x) noexcept + { + return x; + } + + inline number_unsigned_t remove_sign(number_integer_t x) noexcept + { + assert(x < std::numeric_limits::max()); + return static_cast(-(x + 1)) + 1; + } + private: /// the output of the serializer output_adapter_t o = nullptr;