C#: How to convert long to ulong

后端 未结 5 1864
旧巷少年郎
旧巷少年郎 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 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.

提交回复
热议问题