JChristensen / DS3232RTC

Arduino Library for Maxim Integrated DS3232 and DS3231 Real-Time Clocks
GNU General Public License v3.0
394 stars 137 forks source link

Issue with the function dec2bcd #36

Closed ruggi99 closed 7 years ago

ruggi99 commented 7 years ago

In my opinion, the function:

uint8_t DS3232RTC::dec2bcd(uint8_t n)
{
    return n + 6 * (n / 10);
}

should be written as:

uint8_t DS3232RTC::dec2bcd(uint8_t n)
{
    return n + 6 * floor(n / 10);
}

because (n / 10) is double in c++, and when it's multiplicated by 6 it gives wrong results. Example: dec2bcd(64) returns 102 instead of 100.

JChristensen commented 7 years ago

Really? What did you test the code on? The default data type in C++ is always an integer. The size depends on the machine (e.g. 16 bit vs. 32 bit) but it's never a double. I ran the code below with the indicated results.

// testing dec2bcd
// j.christensen 11jan2017
// running on an arduino uno, this returns:
// 100
// 100
// 64
// 64

uint8_t dec2bcd1(uint8_t n) { return n + 6 * (n / 10); }
uint8_t dec2bcd2(uint8_t n) { return n + 6 * floor(n / 10); }

void setup(void)
{
    Serial.begin(9600);
    Serial.println(dec2bcd1(64));
    Serial.println(dec2bcd2(64));
    Serial.println(dec2bcd1(64), HEX);
    Serial.println(dec2bcd2(64), HEX);
}

void loop(void)
{
}