String formatting question

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How would you do the following in C#?

sprintf(szBuff, "MAC Address: %02X-%02X-%02X-%02X-%02X-%02X\n",
MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

assuming that MACData had previously been defined as: unsigned char
MACData[6];
 
The easiest way to do this would be with the string.Format() method, for the
first argument we will use the string
"{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}". Similar to the sprintf method, #
to the right of the : indicates the argument/value used for that location,
while the capitol X specifies that we want a hexadecimal value that is
capitalized, and the 2 indicates the minimum length so that we get 0 padding.

One issue you may run into with this is that C# does not have an unsigned
char type, often for such a thing the byte works the best.

In the end, the code you are looking for would be:

string szBuff = string.Format("{0:X2}-{1:X2}-{2:X2}-{3:X2}-{4:X2}-{5:X2}",
MACData[0], MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

Brendan
 
First, I think you meant,

byte[] MACData = new byte[6];

There is no unsigned char in C#. A byte is equivalent.

Based on this, you might do something like,

string pleaseNoHungarian =
string.Format("{0:x2}-{1:x2}-{2:x2}-{3:x2}-{4:x2}-{5:x2}", MACData[0],
MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);

Frisky

---
Here was my complete sample in Snipet Compiler...

public static void Main()
{
byte[] MACData = new byte[6];
MACData[0] = (byte) 'A';
MACData[1] = (byte) 'B';
MACData[2] = (byte) 'C';
MACData[3] = (byte) 'D';
MACData[4] = (byte) 'E';
MACData[5] = (byte) 'F';

string pleaseNoHungarian =
string.Format("{0:x2}-{1:x2}-{2:x2}-{3:x2}-{4:x2}-{5:x2}", MACData[0],
MACData[1], MACData[2], MACData[3], MACData[4], MACData[5]);
Console.WriteLine(pleaseNoHungarian);
}
 
Back
Top