Fix bigint on conversions to and from 64-bit integers on 32-bit platforms

Fixes BitShares/bitshares_toolkit#150
This commit is contained in:
Eric Frias 2014-06-02 13:32:16 -04:00
parent 04f07aa429
commit 2251d0f241
2 changed files with 24 additions and 5 deletions

View file

@ -11,7 +11,7 @@ namespace fc {
public:
bigint( const std::vector<char>& bige );
bigint( const char* bige, uint32_t l );
bigint( unsigned long i );
bigint(uint64_t value);
bigint( );
bigint( const bigint& c );
bigint( bigint&& c );

View file

@ -6,6 +6,16 @@
#include <fc/exception/exception.hpp>
#ifdef _MSC_VER
# include <stdlib.h>
# define bswap_64(x) _byteswap_uint64(x)
#elif defined(__APPLE__)
# include <libkern/OSByteOrder.h>
# define bswap_64(x) OSSwapInt64(x)
#else
# include <byteswap.h>
#endif
namespace fc {
bigint::bigint( const char* bige, uint32_t l ) {
n = BN_bin2bn( (const unsigned char*)bige, l, NULL );
@ -28,9 +38,10 @@ namespace fc {
return BN_dup( n );
}
bigint::bigint( unsigned long i )
:n(BN_new()) {
BN_set_word( n, i );
bigint::bigint(uint64_t value)
{
uint64_t big_endian_value = bswap_64(value);
n = BN_bin2bn((const unsigned char*)&big_endian_value, sizeof(big_endian_value), NULL);
}
bigint::bigint( const bigint& c ) {
@ -47,7 +58,15 @@ namespace fc {
}
bool bigint::is_negative()const { return BN_is_negative(n); }
int64_t bigint::to_int64()const { return BN_get_word(n); }
int64_t bigint::to_int64() const
{
FC_ASSERT(BN_num_bits(n) <= 63);
size_t size = BN_num_bytes(n);
uint64_t abs_value = 0;
BN_bn2bin(n, (unsigned char*)&abs_value + (sizeof(uint64_t) - size));
return BN_is_negative(n) ? -bswap_64(abs_value) : bswap_64(abs_value);
}
int64_t bigint::log2()const { return BN_num_bits(n); }
bool bigint::operator < ( const bigint& c )const {