div100()
Fast divisions by 10, 100 or 1000.
The quotient divided by 10, 100 or 1000 and the remainder Calculate the quotient and remainder.
In some cases, such as sensor values, the value multiplied by 100 may be passed as a uint16_t
type, but since calculation processing on a microcontroller without a division circuit takes a reasonable amount of time, the calculation is performed by approximate calculation and correction using addition, subtraction, multiplication and bit shift.
Pass val
as the value to be calculated, rem
as the variable to store the remainder, and neg
as the variable to store the sign.
The return value is the quotient value (always positive), rem
stores the remainder value (always positive), and neg
is true
if negative.
The constraints of the calculation algorithm (overflow) determine the range of possible values for div100()
and div1000()
. The div100()
corresponds to values from -9999999 to 9999999, and the div1000()
corresponds to values from -999999999 to 99999999.
Approximate formula to obtain the quotient
Usage examples
Calculation speed
Approx. 10 times faster.
Output results
The div_result_i32
class, which stores the result of division, has a format()
method to obtain a _div_chars
class object. The _div_chars()
class object contains a string buffer and has methods to access the string buffer as const char*
type. It also implements the <<
operator for Serial
objects.
The first parameter dig_quo
of the format()
method specifies the number of output digits (not including the sign part). If the number of output digits is not sufficient (hereafter referred to as missing digits
), it is filled with blanks or 0
. The second parameter opt
specifies the format.
DIVFMT::STD
Standard output, with missing digits filled in with spaces and -
appended only for negative values.
DIVFMT::PAD_ZERO
Missing digits are filled with 0
.
DIVFMT::SIGN_PLUS
A +
sign is also added to positive values.
DIVFMT::PAD_ZERO_SIGN_PLUS
Missing digits are filled with 0
and a +
sign is also added to positive values.
DIVFMT::SIGN_SPACE
For positive values, a space is added in place of the +
sign.
DIVFMT::PAD_ZERO_SIGN_SPACE
Missing digits are filled with 0
, and a space is added in place of the +
sign for positive values.
Example
Background
Since division is a costly operation in the TWELITE wireless microcontroller, we added a division algorithm with a limited purpose.
In the library, some sensor values such as temperature and humidity are expressed using 100 times the value (2512 for 25.12°C), so we defined a simple procedure to obtain the quotient divided by 100 and the remainder.
As for dev_result_i32::format()
, it is to avoid complications when formatting output.
最終更新