C#: How to convert long to ulong
Asked Answered
D

5

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.

Doctrinal answered 27/3, 2009 at 5:36 Comment(1)
Somewhat confused what you're asking here buddy - longs, byte arrays, and ints - can you elaborate ?Somniferous
N
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;
Nucleolar answered 27/3, 2009 at 5:40 Comment(1)
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).aspxCarolinacaroline
L
7

Try:

Convert.ToUInt32()
Leprose answered 27/3, 2009 at 5:41 Comment(0)
B
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.

Berkeleian answered 24/12, 2014 at 13:21 Comment(0)
S
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.

Somniferous answered 27/3, 2009 at 5:41 Comment(5)
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.Deneendenegation
It won't, but the first bit will be interpreted as the most significant bit instead of the sign bit.Transcontinental
It won't throw. You should consider revise your answer otherwise it could be misleading.Cranky
@Cranky indeed. Updated.Travertine
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)Opulence
M
1
Int32 i = 17;
UInt32 j = (UInt32)i;

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

Megasporangium answered 27/3, 2009 at 5:42 Comment(2)
I think John is referring to "old" longs in C or C++ that were 32 bits wide.Nucleolar
I meant that he referred to it out of habit.Nucleolar

© 2022 - 2024 — McMap. All rights reserved.