[英]C#: How to convert long to ulong
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 ++中没有问题。
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;
尝试:
Convert.ToUInt32()
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. 如您所见,即使对于负值,也会完全保留这些位。
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#不会抛出异常。
Int32 i = 17;
UInt32 j = (UInt32)i;
EDIT: question is unclear whether you have a long or an int? 编辑:问题是不清楚你有长期还是国际?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.