Skip to content

Commit

Permalink
Add integer to NAF conversion
Browse files Browse the repository at this point in the history
Added new `bigint` methods `to_naf` & `to_rnaf` which converts integer to non-adjacent form (NAF).
  • Loading branch information
smlu committed Nov 21, 2023
1 parent ad2fa61 commit ecf25df
Show file tree
Hide file tree
Showing 2 changed files with 211 additions and 2 deletions.
38 changes: 37 additions & 1 deletion include/ack/bigint.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
#include <bit>
#include <cstdlib>
#include <cstddef>
#include <vector>
#include <type_traits>

namespace ack {
Expand Down Expand Up @@ -1448,6 +1449,41 @@ namespace ack {
return data;
}

/**
* Converts this integer to non-adjacent form (NAF).
* @return NAF representation of this integer.
*/
[[nodiscard]] inline std::vector<char> to_naf() const
{
std::vector<char> nafv;
nafv.reserve( bit_length() + 1 );
auto num = *this;
while ( num > 0U ) {
if ( num.is_odd() ) {
int32_t nd;
(num % 4).get_int32( nd );
nd = 2 - nd;
nafv.push_back( nd );
num -= nd;
} else {
nafv.push_back( 0 );
}
num >>= 1;
}
return nafv;
}

/**
* Converts this integer to reversed non-adjacent form (NAF).
* @return reversed NAF representation of this integer.
*/
[[nodiscard]] inline std::vector<char> to_rnaf() const
{
auto naf = to_naf();
std::reverse(naf.begin(), naf.end());
return naf;
}

constexpr void clear()
{
*this = 0;
Expand Down Expand Up @@ -1623,7 +1659,7 @@ namespace ack {
* @param n - Reference of type int32_t to receive extracted integer.
* @return true if integer could be extracted otherwise false.
*/
constexpr const bool get_int32(int32_t& n) const
constexpr bool get_int32(int32_t& n) const
{
static_assert( sizeof(word_t) == sizeof(uint32_t) );
if (word_length() > 1) {
Expand Down
Loading

0 comments on commit ecf25df

Please sign in to comment.