簡體   English   中英

代碼高爾夫:C#:將 ulong 轉換為十六進制字符串

[英]Code Golf: C#: Convert ulong to Hex String

我嘗試編寫一個擴展方法來接收 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;
}

解決方案實際上非常簡單,您可以深入研究NumberFormatInfo類,而不是使用各種怪癖將數字格式化為十六進制。

您的問題的解決方案如下...

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

雖然我不會為此用途制作擴展方法。

您可以使用 string.format:

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

檢查C#中的字符串格式以獲取有關格式化輸出的更全面的“操作方法”。

在 C# 6 中,您可以使用字符串插值:

$"0x{variable:X}"

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM