C#: How to convert long to ulong

六月ゝ 毕业季﹏ 提交于 2019-12-04 02:21:54

A simple cast is all you need. Since it's possible to lose precision doing this, the conversion is explicit.

long x = 10;
ulong y = (ulong)x;

Try:

Convert.ToUInt32()
Int32 i = 17;
UInt32 j = (UInt32)i;

EDIT: question is unclear whether you have a long or an int?

Given this function:

string test(long vLong)
{
    ulong vULong = (ulong)vLong;
    return string.Format("long hex: {0:X}, ulong hex: {1:X}", vLong, vULong);
}

And this usage:

    string t1 = test(Int64.MinValue);
    string t2 = test(Int64.MinValue + 1L);
    string t3 = test(-1L);
    string t4 = test(-2L);

This will be the result:

    t1 == "long hex: 8000000000000000, ulong hex: 8000000000000000"
    t2 == "long hex: 8000000000000001, ulong hex: 8000000000000001"
    t3 == "long hex: FFFFFFFFFFFFFFFF, ulong hex: FFFFFFFFFFFFFFFF"
    t4 == "long hex: FFFFFFFFFFFFFFFE, ulong hex: FFFFFFFFFFFFFFFE"

As you can see the bits are preserved completely, even for negative values.

Chris

To convert a long to a ulong, simply cast it:

long a;
ulong b = (ulong)a;

C# will NOT throw an exception if it is a negative number.

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