简体   繁体   中英

Code Golf: C#: Convert ulong to Hex String

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

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.

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.

In C# 6 you can use string interpolation:

$"0x{variable:X}"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM