Skip to content

Commit

Permalink
Implemented the two loops
Browse files Browse the repository at this point in the history
  • Loading branch information
bblanchon committed Jul 8, 2017
1 parent 37fc6ca commit 0669521
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/ArduinoJson/Polyfills/normalize.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ int16_t normalize(T& value) {
using namespace TypeTraits;
int16_t powersOf10 = 0;

// TODO: remove hardcoded 8
int8_t index = sizeof(T) == 8 ? 8 : 5;
int bit = 1 << index;

if (value >= ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD) {
int bit = 256;
for (int8_t index = 8; index >= 0; index--) {
for (; index >= 0; index--) {
if (value >= FloatTraits<T>::positiveBinaryPowerOfTen(index)) {
value /= FloatTraits<T>::positiveBinaryPowerOfTen(index);
powersOf10 = int16_t(powersOf10 + bit);
Expand All @@ -31,8 +31,7 @@ int16_t normalize(T& value) {
}

if (value > 0 && value <= ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD) {
int bit = 256;
for (int8_t index = 8; index >= 0; index--) {
for (; index >= 0; index--) {
if (value / 10 < FloatTraits<T>::negativeBinaryPowerOfTen(index)) {
value *= FloatTraits<T>::positiveBinaryPowerOfTen(index);
powersOf10 = int16_t(powersOf10 - bit);
Expand Down
1 change: 1 addition & 0 deletions test/Polyfills/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
add_executable(PolyfillsTests
isFloat.cpp
isInteger.cpp
normalize.cpp
parseFloat.cpp
parseInteger.cpp
)
Expand Down
43 changes: 43 additions & 0 deletions test/Polyfills/normalize.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright Benoit Blanchon 2014-2017
// MIT License
//
// Arduino JSON library
// https://bblanchon.github.io/ArduinoJson/
// If you like this project, please add a star!

#include <ArduinoJson/Polyfills/normalize.hpp>
#include <catch.hpp>

using namespace ArduinoJson::Polyfills;

TEST_CASE("normalize<double>()") {
SECTION("1.7976931348623157E+308") {
double value = 1.7976931348623157E+308;
int exp = normalize(value);
REQUIRE(value == Approx(1.7976931348623157));
REQUIRE(exp == 308);
}

SECTION("4.94065645841247e-324") {
double value = 4.94065645841247e-324;
int exp = normalize(value);
REQUIRE(value == Approx(4.94065645841247));
REQUIRE(exp == -324);
}
}

TEST_CASE("normalize<float>()") {
SECTION("3.40282347E+38") {
float value = 3.40282347E+38f;
int exp = normalize(value);
REQUIRE(value == Approx(3.40282347f));
REQUIRE(exp == 38);
}

SECTION("1.4e-45") {
float value = 1.4e-45f;
int exp = normalize(value);
REQUIRE(value == Approx(1.4).epsilon(0.001));
REQUIRE(exp == -45);
}
}

0 comments on commit 0669521

Please sign in to comment.