C#: How to convert long to ulong

后端 未结 5 1819
旧巷少年郎
旧巷少年郎 2021-02-20 08:28

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.

相关标签:
5条回答
  • 2021-02-20 08:59
    Int32 i = 17;
    UInt32 j = (UInt32)i;
    

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

    0 讨论(0)
  • 2021-02-20 09:00

    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.

    0 讨论(0)
  • 2021-02-20 09:03

    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;
    
    0 讨论(0)
  • 2021-02-20 09:06

    Try:

    Convert.ToUInt32()
    
    0 讨论(0)
  • 2021-02-20 09:12

    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.

    0 讨论(0)
提交回复
热议问题