Setting from string

This commit is contained in:
Alex Dyachenko 2014-03-23 23:39:32 -04:00
parent 6c0b1be123
commit fc6bfb6f4a
3 changed files with 41 additions and 3 deletions

View File

@ -93,6 +93,31 @@ namespace MPIR.Tests.HugeIntTests
} }
} }
[TestMethod]
public void FromString()
{
using (var a = new HugeInt())
{
var n = "98762934876529834765234123984761";
a.SetTo(n);
Assert.AreEqual(n, a.ToString());
n = "-98ABCDEF876529834765234123984761";
a.SetTo(n, 16);
Assert.AreEqual(n, a.ToString(-16));
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void FromInvalidString()
{
using (var a = new HugeInt())
{
a.SetTo("12345A");
}
}
//todo truncated test //todo truncated test
} }
} }

View File

@ -104,10 +104,20 @@ namespace MPIR
if(!success) if(!success)
{ {
DeallocateStruct(); DeallocateStruct();
throw gcnew ArgumentException("InvalidNumber", "value"); throw gcnew ArgumentException("Invalid number", "value");
} }
} }
void HugeInt::SetTo(String^ value, int base)
{
IntPtr ptr = Marshal::StringToHGlobalAnsi(value);
bool success = 0 == mpz_set_str(_value, (char*)(void*)ptr, base);
Marshal::FreeHGlobal(ptr);
if(!success)
throw gcnew ArgumentException("Invalid number", "value");
}
HugeInt^ HugeInt::FromLong(mpir_si value) HugeInt^ HugeInt::FromLong(mpir_si value)
{ {
auto result = gcnew HugeInt(); auto result = gcnew HugeInt();

View File

@ -359,10 +359,13 @@ namespace MPIR
//conversions //conversions
mpir_ui ToUlong() { return mpz_get_ui(_value); } mpir_ui ToUlong() { return mpz_get_ui(_value); }
void SetTo(mpir_ui value) { mpz_set_ui(_value, value); }
mpir_si ToLong() { return mpz_get_si(_value); } mpir_si ToLong() { return mpz_get_si(_value); }
void SetTo(mpir_si value) { mpz_set_si(_value, value); }
double ToDouble() { return mpz_get_d(_value); } double ToDouble() { return mpz_get_d(_value); }
void SetTo(mpir_ui value) { mpz_set_ui(_value, value); }
void SetTo(mpir_si value) { mpz_set_si(_value, value); }
void SetTo(double value) { mpz_set_d(_value, value); } void SetTo(double value) { mpz_set_d(_value, value); }
void SetTo(String^ value) { SetTo(value, 10); }
void SetTo(String^ value, int base);
}; };
}; };