From 935cb39dff3d53e90278a814b02a8b2362e0798d Mon Sep 17 00:00:00 2001 From: Tom Pittenger Date: Fri, 21 Aug 2020 09:12:39 -0700 Subject: [PATCH] AP_Math: add function to convert any base to any base Example: convert dec 12345 to 0x12345 or dec 1200 to octal 1200 --- libraries/AP_Math/AP_Math.cpp | 17 +++++++++++++++++ libraries/AP_Math/AP_Math.h | 3 +++ 2 files changed, 20 insertions(+) diff --git a/libraries/AP_Math/AP_Math.cpp b/libraries/AP_Math/AP_Math.cpp index 326b5ec310..8d52bfa217 100644 --- a/libraries/AP_Math/AP_Math.cpp +++ b/libraries/AP_Math/AP_Math.cpp @@ -128,6 +128,23 @@ float throttle_curve(float thr_mid, float alpha, float thr_in) return thr_out; } +/* + * Convert any base number to any base number. Example octal(8) to decimal(10) + * baseIn: base of input number + * baseOut: base of output number + * inputNumber: value currently in base "baseIn" to be converted to base "baseOut" + */ +uint32_t convertMathBase(const uint8_t baseIn, const uint8_t baseOut, uint32_t inputNumber) +{ + uint32_t outputNumber = 0; + + for (uint8_t i=0; inputNumber != 0; i++) { + outputNumber += (inputNumber % baseOut) * powf(float(baseIn), i); + inputNumber /= baseOut; + } + return outputNumber; +} + template T wrap_180(const T angle) { diff --git a/libraries/AP_Math/AP_Math.h b/libraries/AP_Math/AP_Math.h index 01912a3478..85dd518df7 100644 --- a/libraries/AP_Math/AP_Math.h +++ b/libraries/AP_Math/AP_Math.h @@ -265,6 +265,9 @@ constexpr float expo_curve(float alpha, float input); */ float throttle_curve(float thr_mid, float alpha, float thr_in); +// Convert any base number to any base number. Example octal(8) to decimal(10) +uint32_t convertMathBase(const uint8_t baseIn, const uint8_t baseOut, uint32_t inputNumber); + /* simple 16 bit random number generator */ uint16_t get_random16(void);