string.format()与自定义十六进制格式

时间:2014-01-24 13:23:43

标签: c# string string-formatting

我需要将整数格式化为MAC地址(01-1A-1B-2B-30等)。有没有办法直接使用string.format()? 到目前为止我所有的考试都失败了:

string.Format("{0:X}", 1234567); //Output: 12D687 It is hex, but not formatted
string.Format("{0:00-00-00-00}", 1234567); //Output: 01-23-45-67 Formatted, but not hex
string.Format("{0:00-00-00-00}", string.Format("{0:X}", 1234567)); //Output: 01-23-45-67 Also dosn't work and is ugly.
string.Format("{0:X00-00-00-00}", 1234567); //Output: X01-23-45-67 Well. Still no success here.

5 个答案:

答案 0 :(得分:2)

这将包括-分隔符;

BitConverter.ToString(BitConverter.GetBytes(1234567))

答案 1 :(得分:1)

使用

BitConverter.ToString(BitConverter.GetBytes(1234567))

答案 2 :(得分:0)

您需要为每个字节都有一个占位符,并将整数作为数组传递:

// We have a format string that spits out hex for each byte seperated by a dash.
// ToString expects either a params or an object array, so let's get the bytes
// as a byte array, and convert it to an array of object
String.Format("{0:X}-{1:X}-{2:X}-{3:X}", BitConverter.GetBytes(1234567).Cast<Object>().ToArray())

答案 3 :(得分:0)

将其转换为十六进制字符串后,您可以使用此方法将其拆分为chunkSize 2,然后使用连字符重新加入

void Main()
{
    var str = string.Format("{0:X}", 12345678);
    var splits = Split(str, 2);
    var rejoinedSplits = string.Join("-",splits);
    Console.WriteLine (rejoinedSplits); //tested in linqpad, gave me BC-61-4E
}
static IEnumerable<string> Split(string str, int chunkSize)
{
      return Enumerable.Range(0, str.Length / chunkSize).Select(i => str.Substring(i * chunkSize, chunkSize));
}

答案 4 :(得分:0)

使用以下功能将每4位数字分开:

    public static string NumberToHexStr<T>(T obj) where T : IComparable, IFormattable, IConvertible // Any Number Type
    {
        string strHex = string.Format("0x{0:X2}", obj);
        if (strHex.Length > 6)
        {
            while (((strHex.Length - 2) % 4) != 0)
                strHex = strHex.Insert(2, "0");

            int nIndex = strHex.Length - 4;
            while (nIndex > 2)
            {
                strHex = strHex.Insert(nIndex, " ");
                nIndex -= 4;
            }
        }

        return strHex;
    }

示例:1,407,392,063,619,074将显示为0x0005 0004 0003 0002