Code Golf: C #: convert ulong to hexadecimal string

I tried writing an extension method to take ulong and return a string that represents the provided value in hexadecimal without leading zeros. I was not very happy with what I came up with ... is there a better way to do this using the standard .NET libraries?

public static string ToHexString(this ulong ouid)
{
    string temp = BitConverter.ToString(BitConverter.GetBytes(ouid).Reverse().ToArray()).Replace("-", "");

    while (temp.Substring(0, 1) == "0")
    {
        temp = temp.Substring(1);
    }

    return "0x" + temp;
}
+3
source share
2 answers

The solution is actually really simple, instead of using all kinds of quirks to format the number in hexadecimal, you can dig a class in NumberFormatInfo .

The solution to your problem is as follows:

return string.Format("0x{0:X}", temp);

Although I would not have made an extension method for this use.

+16

string.format:

string.Format("0x{0:X4}",200);

# "" .

+3

Source: https://habr.com/ru/post/1734082/


All Articles