Difference between long and int in C#?

坚强是说给别人听的谎言 提交于 2019-12-20 10:17:37

问题


What is the actual difference between a long and an int in C#? I understand that in C/C++ long would be 64bit on some 64bit platforms(depending on OS of course) but in C# it's all running in the .NET runtime, so is there an actual distinction?

Another question: can an int hold a long(by cast) without losing data on all platforms?


回答1:


an int (aka System.Int32 within the runtime) is always a signed 32 bit integer on any platform, a long (aka System.Int64) is always a signed 64 bit integer on any platform. So you can't cast from a long with a value above Int32.MaxValue or below Int32.MinValuewithout losing data.




回答2:


int in C#=> System.Int32=>from -2,147,483,648 to 2,147,483,647.

long in C#=> System.Int64 =>from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

If your long data exceeds the range of int, and you use Convert.ToInt32 then it will throw OverflowException, if you use explicit cast then the result would be unexpected.




回答3:


int is 32 bits in .NET. long is 64-bits. That is guaranteed. So, no, an int can't hold a long without losing data.

There's a type whose size changes depending on the platform you're running on, which is IntPtr (and UIntPtr). This could be 32-bits or 64-bits.




回答4:


Sure is a difference - In C#, a long is a 64 bit signed integer, an int is a 32 bit signed integer, and that's the way it always will always be.

So in C#, a long can hold an int, but an int cannot hold a long.

C/C++ that question is platform dependent.




回答5:


In C#, an int is a System.Int32 and a long is a System.Int64; the former is 32-bits and the later 64-bits.

C++ only provides vague guarantees about the size of int/long, in comparison (you can dig through the C++ standard for the exact, gory, details).




回答6:


I think an int is a 32-bit integer, while a long is a 64-bit integer.



来源:https://stackoverflow.com/questions/1918436/difference-between-long-and-int-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!