Code Golf:C#:将ulong转换为Hex String

Lan*_*don 4 c# hex

我尝试编写一个扩展方法来接收ulong并返回一个字符串,该字符串以十六进制格式表示提供的值,没有前导零.我对我提出的建议并不满意......使用标准.NET库是不是更好的方法呢?

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;
}
Run Code Online (Sandbox Code Playgroud)

cyb*_*zed 18

解决方案实际上非常简单,而不是使用各种怪癖将数字格式化为十六进制,您可以深入研究NumberFormatInfo类.

您的问题的解决方案如下......

return string.Format("0x{0:X}", temp);
Run Code Online (Sandbox Code Playgroud)

虽然我不会为这种用途做出扩展方法.

  • 不需要ToUpper()...只是我们X而不是x matey :) (2认同)