+ 2
[SOLVED] Can't convert signed int to unsigned long
int n = -1; Write( Convert.ToUInt64(n) ); // Error - Value was either too large or too small for a UInt64 But it works for `Int64`. What's the correct way to do so?
3 odpowiedzi
+ 1
According to https://docs.microsoft.com/en-us/dotnet/api/system.convert.touint64?view=net-5.0#System_Convert_ToUInt64_System_Int32_
The function raises exception when given argument was less than zero.
(Edit)
A manual type casting work may help, but I'm not sure it's worth it.
int n = -1;
UInt64 un = 0;
if (n < 0)
{
un = Convert.ToUInt64( UInt64.MaxValue - ( UInt64 ) Math.Abs( n ) );
}
else
{
un = Convert.ToUInt64( n );
}
Console.Write( un );
+ 2
https://code.sololearn.com/c8MK8nJIk7Aq/?ref=app
Can be usefull for you
+ 1
UInt range is between 0 to 4,294,967,295 while int range is between -2,147,483,648 to 2,147,483,647 , so u can't convert negative numbers to Unsigned integer