C#: How to convert long to ulong

31,019

Solution 1

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;

Solution 2

Try:

Convert.ToUInt32()

Solution 3

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.

Solution 4

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.

Solution 5

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

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

Share:
31,019
P. Duw
Author by

P. Duw

Updated on July 09, 2022

Comments

  • P. Duw
    P. Duw almost 2 years

    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.

  • Matthew Olenik
    Matthew Olenik about 15 years
    I think John is referring to "old" longs in C or C++ that were 32 bits wide.
  • Tracker1
    Tracker1 about 15 years
    I don't beleive that this throws an exception with a negative value, but will not be what you expect... don't have .net on here (laptop), or would test it.
  • Matthew Olenik
    Matthew Olenik about 15 years
    I meant that he referred to it out of habit.
  • Josh Stodola
    Josh Stodola almost 14 years
    Isn't this possible to overflow with big negatives? You can use unchecked to truncate instead: msdn.microsoft.com/en-us/library/a569z7k8(VS.71).aspx
  • DuneCat
    DuneCat about 11 years
    It won't, but the first bit will be interpreted as the most significant bit instead of the sign bit.
  • KFL
    KFL about 11 years
    It won't throw. You should consider revise your answer otherwise it could be misleading.
  • Patrick Hofman
    Patrick Hofman over 8 years
    @KFL indeed. Updated.
  • adrianm
    adrianm over 8 years
    If it throws or not is a compiler settings (Build/Advanced/Check for arithmetic overflow/underflow). To be safe you should always wrap it like ulong b = unchecked((ulong)a)