From c8839553c000baeccb5e2b3f7c43aa8d79849a7d Mon Sep 17 00:00:00 2001 From: Daniel Larimer Date: Sun, 28 Jul 2013 02:13:31 -0400 Subject: [PATCH] updated 128bit int math and bigint --- include/fc/crypto/bigint.hpp | 1 + include/fc/uint128.hpp | 11 +++++++++-- src/crypto/bigint.cpp | 7 +++++++ src/uint128.cpp | 13 +++++++++++++ 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/include/fc/crypto/bigint.hpp b/include/fc/crypto/bigint.hpp index 130233f..e7117ae 100644 --- a/include/fc/crypto/bigint.hpp +++ b/include/fc/crypto/bigint.hpp @@ -45,6 +45,7 @@ namespace fc { bigint operator *= ( const bigint& a ); bigint& operator += ( const bigint& a ); bigint& operator <<= ( uint32_t i ); + bigint& operator >>= ( uint32_t i ); bigint operator - ( const bigint& a )const; diff --git a/include/fc/uint128.hpp b/include/fc/uint128.hpp index 9fe280d..f0da0f8 100644 --- a/include/fc/uint128.hpp +++ b/include/fc/uint128.hpp @@ -4,6 +4,7 @@ namespace fc { + class bigint; /** * @brief an implementation of 128 bit unsigned integer * @@ -11,8 +12,6 @@ namespace fc class uint128 { - uint64_t hi; - uint64_t lo; public: uint128():hi(0),lo(0){}; @@ -23,8 +22,10 @@ namespace fc uint128( const std::string& s ); uint128( uint64_t _h, uint64_t _l ) :hi(_h),lo(_l){} + uint128( const fc::bigint& bi ); operator std::string()const; + operator fc::bigint()const; bool operator == ( const uint128& o )const{ return hi == o.hi && lo == o.lo; } bool operator != ( const uint128& o )const{ return hi != o.hi || lo != o.lo; } @@ -67,8 +68,14 @@ namespace fc friend bool operator <= ( const uint128& l, const uint128& r ) { return l == r || l < r; } uint32_t to_integer()const { return lo; } + uint64_t to_uint64()const { return lo; } uint64_t low_bits()const { return lo; } uint64_t high_bits()const { return hi; } + + private: + uint64_t hi; + uint64_t lo; + }; static_assert( sizeof(uint128) == 2*sizeof(uint64_t), "validate packing assumptions" ); diff --git a/src/crypto/bigint.cpp b/src/crypto/bigint.cpp index e1a7b29..d41224c 100644 --- a/src/crypto/bigint.cpp +++ b/src/crypto/bigint.cpp @@ -133,6 +133,13 @@ namespace fc { *this = std::move(tmp); return *this; } + bigint& bigint::operator >>= ( uint32_t i ) + { + bigint tmp; + BN_rshift( tmp.n, n, i ); + std::swap(*this,tmp); + return *this; + } bigint& bigint::operator <<= ( uint32_t i ) { diff --git a/src/uint128.cpp b/src/uint128.cpp index 58919de..71f2a42 100644 --- a/src/uint128.cpp +++ b/src/uint128.cpp @@ -1,5 +1,6 @@ #include #include +#include namespace fc { @@ -111,6 +112,18 @@ namespace fc } + #define bswap64(y) (((uint64_t)ntohl(y)) << 32 | ntohl(y>>32)) + uint128::operator bigint()const + { + auto tmp = uint128( bswap64( hi ), bswap64( lo ) ); + bigint bi( (char*)&tmp, sizeof(tmp) ); + return bi; + } + uint128::uint128( const fc::bigint& bi ) + { + *this = uint128( std::string(bi) ); // TODO: optimize this... + } + uint128::operator std::string ()const { if(*this == 0) { return "0"; }