代码之家  ›  专栏  ›  技术社区  ›  Josh

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

  •  2
  • Josh  · 技术社区  · 16 年前

    // 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 ""
    

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


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

    我可能会咬紧牙关,将integer属性设置为可为null的int,并在使用zero-bleh时使用null。

    1 回复  |  直到 16 年前
        1
  •  2
  •   Community Mohan Dere    5 年前

    以下格式字符串几乎正确:

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

    给予:

    0x0000000A

    0xFFFFF6

    我仍在尝试为0使用“”。

    编辑2:follow扩展方法将返回格式正确的字符串,包括+'ves、'ves和0。参数长度是十六进制字符串中所需的字符数(不包括前面的'0x')。

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