Skip to content

Commit 9310b98

Browse files
author
jparisu
committed
fix module
Signed-off-by: jparisu <[email protected]>
1 parent bc6b360 commit 9310b98

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

ddsrouter_utils/src/cpp/math/math.cpp

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ bool is_even(
3131
return (number & 0x1) == 0;
3232
}
3333

34+
bool is_power_of_2(
35+
uint32_t number) noexcept
36+
{
37+
return number && (!(number & (number-1)));
38+
}
39+
3440
uint32_t fast_module(
3541
uint32_t dividend,
3642
uint32_t divisor) noexcept
@@ -52,9 +58,9 @@ uint32_t fast_module(
5258
// Optimize to 4 operations [if, if, if, and]
5359
return dividend & 1;
5460
}
55-
else if (is_even(divisor))
61+
else if (is_power_of_2(divisor))
5662
{
57-
// Optimize to 6 operations [if, if, if, if(and), and]
63+
// Optimize to ~6 operations [if, if, if, if(and), and]
5864
return dividend & (divisor - 1);
5965
}
6066
else
@@ -80,11 +86,25 @@ uint32_t fast_division(
8086
// Optimize to 2 operation [if, if]
8187
return 1;
8288
}
89+
else if (divisor == 1)
90+
{
91+
// Optimize to 3 operations [if, if, if]
92+
return dividend;
93+
}
8394
else if (divisor == 2)
8495
{
85-
// Optimize to 4 operations [if, if, if, swift]
96+
// Optimize to 5 operations [if, if, if, if, swift]
8697
return (dividend >> 1);
8798
}
99+
else if (is_power_of_2(divisor))
100+
{
101+
while (divisor != 1)
102+
{
103+
dividend >>= 1;
104+
divisor >>= 1;
105+
}
106+
return dividend;
107+
}
88108
else
89109
{
90110
// Not optimum

0 commit comments

Comments
 (0)