Format your MAC address with string.Format in C #

I have a mac address that is formatted as 0018103AB839 and I want to display it as: 00:18:10:3A:B8:39

I am trying to do this with string.Format , but I cannot find the exact syntax.

right now i am trying something like this:

  string macaddress = 0018103AB839; string newformat = string.Format("{0:00:00:00:00:00:00}", macaddress); 

Is it possible? or should i use string.Insert ?

+8
string c #
source share
4 answers

Reformat the string to display it as a MAC address:

 var macadres = "0018103AB839"; var regex = "(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})"; var replace = "$1:$2:$3:$4:$5:$6"; var newformat = Regex.Replace(macadres, regex, replace); // newformat = "00:18:10:3A:B8:39" 

If you want to check the input line, use this regex (thanks J0HN):

 var regex = String.Concat(Enumerable.Repeat("([a-fA-F0-9]{2})", 6)); 
+6
source share
 string input = "0018103AB839"; var output = string.Join(":", Enumerable.Range(0, 6) .Select(i => input.Substring(i * 2, 2))); 
+3
source share
 var strings = macadres .Select((value, index) => new { Pair = index / 2, value }) .GroupBy(g => g.Pair ) .Select(g => g.Aggregate("", (accumulated, elem) => accumulated+elem.value)); string formatted = String.Join(":", strings); 
+1
source share

Suppose we have a Mac address stored in long. Here's how to do it in a formatted string:

 ulong lMacAddr = 0x0018103AB839L; string strMacAddr = String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", (lMacAddr >> (8 * 5)) & 0xff, (lMacAddr >> (8 * 4)) & 0xff, (lMacAddr >> (8 * 3)) & 0xff, (lMacAddr >> (8 * 2)) & 0xff, (lMacAddr >> (8 * 1)) & 0xff, (lMacAddr >> (8 * 0)) & 0xff); 
0
source share

All Articles