C#:如何将 long 转换为 ulong

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/688667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:33:57  来源:igfitidea点击:

C#: How to convert long to ulong

c#long-integerulong

提问by Ivan Prodanov

If i try with BitConverter,it requires a byte array and i don't have that.I have a Int32 and i want to convert it to UInt32.

如果我尝试使用 BitConverter,它需要一个字节数组,而我没有。我有一个 Int32,我想将它转换为 UInt32。

In C++ there was no problem with that.

在 C++ 中,这没有问题。

采纳答案by Matthew Olenik

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;

回答by Chris

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

要将 long 转换为 ulong,只需将其强制转换:

long a;
ulong b = (ulong)a;

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

如果它是负数,C# 不会抛出异常。

回答by SirDemon

Try:

尝试:

Convert.ToUInt32()

回答by Mitch Wheat

Int32 i = 17;
UInt32 j = (UInt32)i;

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

编辑:问题不清楚你是 long 还是 int?

回答by intrepidis

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.

如您所见,即使对于负值,位也被完全保留。