将自定义数字格式字符串与十六进制格式字符串

时间:2010-01-13 16:35:47

标签: .net formatting string-formatting

我有一种情况,我需要根据它是否为零来格式化整数。使用自定义数字格式字符串,可以使用分号作为分隔符来实现。请考虑以下事项:

// this works fine but the output is decimal
string format = "{0:0000;-0000;''}";
Console.WriteLine(format,  10); // outputs "0010"
Console.WriteLine(format, -10); // outputs "-0010"
Console.WriteLine(format,   0); // outputs ""

但是,我想要使用的格式是十六进制。我希望输出更像是:

// this doesn't work
string format = "{0:'0x'X8;'0x'X8;''}";
Console.WriteLine(format,  10); // desired "0x0000000A", actual "0xX8"
Console.WriteLine(format, -10); // desired "0xFFFFFFF6", actual "0xX8"
Console.WriteLine(format,   0); // desired "", actual ""

不幸的是,当使用自定义数字格式字符串时,我不确定如何(如果可能的话)在自定义格式字符串中使用数字的十六进制表示。我所拥有的场景不允许太多的灵活性,因此不能选择两遍格式。无论我做什么都需要表示为String.Format样式格式字符串。

修改
在查看NumberFormatter的Mono源代码(.NET实现只是遵循内部非托管代码)之后,我确认了我的怀疑。十六进制格式字符串被视为特殊情况,它仅作为标准格式字符串提供,不能在自定义格式字符串中使用。由于三部分格式字符串不能与标准格式字符串一起使用,我几乎是S.O.L。

我可能只是咬住子弹并使整数属性成为可以为空的int并使用null我使用零 - bleh。

1 个答案:

答案 0 :(得分:2)

以下格式字符串是ALMOST正确的:

string format = "0x{0:X8}";
Console.WriteLine(format, 10);
Console.WriteLine(format, -10);
Console.WriteLine(format, 0);

给出:

  

0X0000000A

     

0xFFFFFFF6

     

00000000

我仍然在努力为''做0。

编辑:我遇到了同样的问题,只有当格式字符串有分隔符''时,X8才会成为文字。正在使用。我只是想在.NET源代码中查看,看看我能看到什么。

编辑2:跟随扩展方法将返回一个格式正确的字符串,用于+'ves,-'ves和0.参数length是十六进制字符串中所需的字符数(不包括'0x'在前面)。

    public static string ToHexString(this int source, int length)
    {
        return (source != 0) ? string.Format("0x{0:X" + length.ToString() + "}",source) : string.Empty;
    }