11

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
  • 31,952
  • 74
  • 168
  • 243
  • 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

23

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,527
  • 26
  • 30
  • 7
    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

Try:

Convert.ToUInt32()
SirDemon
  • 1,730
  • 15
  • 24
5

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,588
  • 1
  • 30
  • 30
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
  • 143,714
  • 19
  • 222
  • 294
Chris
  • 37,118
  • 43
  • 178
  • 226
  • 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
  • 280,588
  • 41
  • 444
  • 526