开发者

Code Golf: C#: Convert ulong to Hex String

开发者 https://www.devze.com 2022-12-21 12:56 出处:网络
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 wit

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开发者_如何学JAVA.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://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号