Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions std/bigint.d
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ public:
assert(cast(long) b2 == -0x01_02_03_04_05_06L);
}


Comment thread
Prashant-900 marked this conversation as resolved.
Outdated
/// Construct a `BigInt` from a built-in integral type.
this(T)(T x) pure nothrow @safe
if (isIntegral!T)
Expand All @@ -188,6 +189,91 @@ public:
opAssign(x);
}

/// Construct `BigInt` from `Int128`
import std.int128 : Int128;
this(Int128 x) pure nothrow @safe {
data = data.init;
opAssign(x);
}

/// Assignment from `Int128`.
BigInt opAssign(T : Int128)(T x) @safe
{
sign = false;

ulong lo = x.data.lo;
long hi = x.data.hi;

// Determine sign and get absolute value
if (hi < 0)
{
sign = true;

// Two's complement negate
lo = ~lo + 1;
hi = ~hi + (lo == 0);
}

// Now (hi, lo) is the positive magnitude
if (hi != 0)
{
ulong[2] mag = [cast(ulong)hi, lo];
data.fromMagnitude(mag[]);
}
else
{
data = lo;
}

if (data.isZero)
sign = false;

return this;
}

///
@safe unittest
{
Int128 x;
BigInt b;
BigInt re;

x = Int128(0L);
b = BigInt(x);
re = BigInt(0L);
assert(b == re);

x = Int128(42L);
b = BigInt(x);
re = BigInt(42L);
assert(b == re);

x = Int128(-42L);
b = BigInt(x);
re = BigInt(-42L);
assert(b == re);

x = Int128(-1L);
b = BigInt(x);
re = BigInt(-1L);
assert(b == re);

x = (Int128(1L) << 100) + Int128(12345L);
b = BigInt(x);
Comment thread
Prashant-900 marked this conversation as resolved.
Outdated
re = (BigInt(1L) << 100) + BigInt(12345L);
assert(b == re);

x = -((Int128(1L) << 100) + Int128(12345L));
b = BigInt(x);
re = -((BigInt(1L) << 100) + BigInt(12345L));
assert(b == re);

x = Int128.min;
b = BigInt(x);
re = -(BigInt(1L) << 127);
assert(b == re);
}

///
@safe unittest
{
Expand Down