Turbofant
Turbofant

Reputation: 531

string.format() with coustom hex-format

I need to format an integer as a MAC-Address (01-1A-1B-2B-30 and so on). Is there a way to to this directly with string.format()? All my attepts so far have failed:

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.

Upvotes: 0

Views: 1054

Answers (5)

Behzad Ebrahimi
Behzad Ebrahimi

Reputation: 1026

Use the following function to separate every 4 digits:

    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;
    }

Example: 1,407,392,063,619,074 will be displayed as 0x0005 0004 0003 0002.

Upvotes: 0

user1968030
user1968030

Reputation:

Use

BitConverter.ToString(BitConverter.GetBytes(1234567))

Upvotes: 1

DLeh
DLeh

Reputation: 24395

Once you turn it into a hex string, you could use this method to split it up into chunkSize 2, then rejoin it with hyphens

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));
}

Upvotes: 0

Alex K.
Alex K.

Reputation: 175766

This will include a - delimiter;

BitConverter.ToString(BitConverter.GetBytes(1234567))

Upvotes: 3

Andy Hopper
Andy Hopper

Reputation: 3678

You need to have a placeholder for each byte, and pass the integer in as an array:

// 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())

Upvotes: 0

Related Questions