4

How do I convert ulong to long with same result as I get in c++.

C++

unsigned long ul = 3633091313;
long l = (long)ul;
l is -661875983

C#

ulong ul = 3633091313;
long l = (long)ul;
l is 3633091313
Teamol
  • 733
  • 1
  • 14
  • 42
  • 1
    You **want** an overflow error? Because that is what the C++ example is, a error. The .NEt Long is a 64 bit signed integer. So the maximum is 9,223,372,036,854,775,807 (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/long) As opposed to native C++ Long is only 32 bit – Christopher Feb 07 '18 at 20:21

1 Answers1

8

C++'s long is often a 32-bit data type. It looks like in your system it does not have enough bits to represent 3633091313, so the result is negative. This behavior is undefined in C++ (relevant Q&A).

In C# that corresponds to converting to int:

UInt64 ul = 3633091313UL;
Int32 l = (int)ul;
Console.WriteLine(l); // prints -661875983

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Maybe we should be using the int[binarity] here, rather then the type alias "int" and "ulong"? The width of the type in memory seems to be a important feature. For whatever wierd reason. – Christopher Feb 07 '18 at 20:24
  • @Christopher You are right, showing the proper size is more descriptive. Thank you! – Sergey Kalinichenko Feb 07 '18 at 20:26