[SOLVED] Can't convert signed int to unsigned long | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

29th Jul 2021, 1:16 PM
Kiwwi#
Kiwwi# - avatar
3 Answers
+ 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 );
29th Jul 2021, 5:24 PM
Ipang
30th Jul 2021, 2:23 AM
NosZanou Officiel
NosZanou Officiel - avatar
+ 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
29th Jul 2021, 4:22 PM
Nima