Code Golf:C#:将 ulong 转换为十六进制字符串
我尝试编写一个扩展方法来接受 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案实际上非常简单,您可以深入研究NumberFormatInfo 类。
您的问题的解决方案如下...
尽管我不会为此用途制定扩展方法。
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...
Though I wouldn't make an extension method for this use.
您可以使用 string.format:
检查C# 中的字符串格式 有关格式化输出的更全面的“操作方法”。
You can use string.format:
Check String Formatting in C# for a more comprehensive "how-to" on formatting output.
在 C# 6 中,您可以使用字符串插值:
$"0x{variable:X}"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
In C# 6 you can use string interpolation:
$"0x{variable:X}"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated