Code Golf: C#: Convert ulong to Hex String

c#, hex

Solution

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

The solution to your problem is as follows...

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

Though I wouldn't make an extension method for this use.

Problem

I tried writing an extension method to take in a ulong and return a string that represents the provided value in hexadecimal format with no leading zeros. I wasn't really happy with what I came up with... is there not a better way to do this using 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; } ```

Original source