Code Golf: C#: Convert ulong to Hex String

11,652

Solution 1

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.

Solution 2

You can use string.format:

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

Check String Formatting in C# for a more comprehensive "how-to" on formatting output.

Solution 3

In C# 6 you can use string interpolation:

$"0x{variable:X}"

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Share:
11,652
Langdon
Author by

Langdon

I thoroughly enjoy writing JavaScript and C#. AngularJS has recently stolen my <3.

Updated on June 05, 2022

Comments

  • Langdon
    Langdon almost 2 years

    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;
    }