Skip to content

Commit

Permalink
ir_commons.hpp - countBits method updated and comments added
Browse files Browse the repository at this point in the history
Others:
1. countBits_negative function removed
2. countBits_positive - minor change in the variable increment step
  • Loading branch information
fenilgmehta committed Jul 17, 2019
1 parent 01f51ac commit 1bf5470
Showing 1 changed file with 13 additions and 16 deletions.
29 changes: 13 additions & 16 deletions src/ir_commons.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,29 +20,26 @@ namespace ir_sort{

while (num > 0) {
num >>= 1;
result += 1;
}

return result;
}

template<typename T>
inline int_fast16_t countBits_negative(const T &negativeNum) {
auto num = static_cast<uint_fast64_t>(-negativeNum);
int_fast16_t result = 0;

while (num > 0) {
num >>= 1;
result += 1;
++result;
}

return result;
}

template<typename T>
inline int_fast16_t countBits(const T &num) {
if (num < 0) return countBits_negative(num);
return countBits_positive(num);
/*
* To understand the working of this function for -ve numbers, try to understand
* the trick used to find 2's complement with Deterministic Finite Automata(DFA)
*
* Trick explanation
* We start from the right and move towards the left, then move towards the
* left leaving all bits unchanged until "1" is encountered. We start flipping
* the bits from the left of the first occurrence of "1".
* */

return ((num > 0) ? countBits_positive(num)
: countBits_positive(-num));
}

//############################################################################
Expand Down

0 comments on commit 1bf5470

Please sign in to comment.