12

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.

Ivan Prodanov
  • 34,634
  • 78
  • 176
  • 248
  • Somewhat confused what you're asking here buddy - longs, byte arrays, and ints - can you elaborate ? – Chris Mar 27 '09 at 05:42

5 Answers5

24

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;
Matthew Olenik
  • 3,577
  • 1
  • 28
  • 31
  • 8
    Isn't this possible to overflow with big negatives? You can use `unchecked` to truncate instead: http://msdn.microsoft.com/en-us/library/a569z7k8(VS.71).aspx – Josh Stodola May 26 '10 at 01:46
7

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.

intrepidis
  • 2,870
  • 1
  • 34
  • 36
7

Try:

Convert.ToUInt32()
SirDemon
  • 1,758
  • 15
  • 24
2

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.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Chris
  • 39,719
  • 45
  • 189
  • 235
  • 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. – Tracker1 Mar 27 '09 at 06:36
  • It won't, but the first bit will be interpreted as the most significant bit instead of the sign bit. – DuneCat Mar 21 '13 at 15:43
  • It won't throw. You should consider revise your answer otherwise it could be misleading. – KFL Apr 11 '13 at 06:21
  • @KFL indeed. Updated. – Patrick Hofman Oct 08 '15 at 13:05
  • 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)` – adrianm Nov 18 '15 at 08:40
1
Int32 i = 17;
UInt32 j = (UInt32)i;

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

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541