AceCommon  1.1
Arduino library for low-level common functions and features with no external dependencies
arithmetic.h
Go to the documentation of this file.
1 /*
2 MIT License
3 
4 Copyright (c) 2018, 2020 Brian T. Park
5 
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12 
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15 
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 SOFTWARE.
23 */
24 
33 #ifndef ACE_COMMON_ARITHMETIC_H
34 #define ACE_COMMON_ARITHMETIC_H
35 
36 #include <stdint.h>
37 
38 namespace ace_common {
39 
45 template<typename T>
46 void incrementMod(T& d, T m) {
47  d++;
48  if (d >= m) d = 0;
49 }
50 
56 template<typename T>
57 void incrementModOffset(T& d, T m, T offset) {
58  d -= offset;
59  d++;
60  if (d >= m) d = 0;
61  d += offset;
62 }
63 
65 inline uint8_t decToBcd(uint8_t val) {
66  return (val / 10 * 16) + (val % 10);
67 }
68 
70 inline uint8_t bcdToDec(uint8_t val) {
71  return (val / 16 * 10) + (val % 16);
72 }
73 
96 inline unsigned long udiv1000(unsigned long n) {
97  unsigned long x = (n >> 8);
98  unsigned long y = (x >> 8);
99  unsigned long z = (y >> 8);
100  return (x >> 2) + 3 * (y >> 1) + 9 * z;
101 }
102 
103 }
104 
105 #endif
ace_common::bcdToDec
uint8_t bcdToDec(uint8_t val)
Convert binary coded decimal to normal decimal numbers.
Definition: arithmetic.h:70
ace_common::incrementModOffset
void incrementModOffset(T &d, T m, T offset)
Increment 'd' mod 'm', with an offset, avoiding '' operator which is expensive for 8-bit processors.
Definition: arithmetic.h:57
ace_common::incrementMod
void incrementMod(T &d, T m)
Increment 'd' mod 'm', avoiding '' operator which is expensive for 8-bit processors.
Definition: arithmetic.h:46
ace_common::udiv1000
unsigned long udiv1000(unsigned long n)
Approximate division by 1000 without using integer division to avoid inefficient integer division ope...
Definition: arithmetic.h:96
ace_common::decToBcd
uint8_t decToBcd(uint8_t val)
Convert normal decimal numbers to binary coded decimal.
Definition: arithmetic.h:65