Question

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.

In C++ there was no problem with that.

Was it helpful?

Solution

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;

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top