14

我有一个格式如下的 mac 地址,0018103AB839我想将其显示为:00:18:10:3A:B8:39

我正在尝试这样做,string.Format但我真的找不到确切的语法。

现在我正在尝试这样的事情:

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

这甚至可能吗?还是我应该使用string.Insert

4

3 回答 3

13

重新格式化字符串以将其显示为 MAC 地址:

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"

如果要验证输入字符串,请使用此正则表达式(感谢 J0HN):

var regex = String.Concat(Enumerable.Repeat("([a-fA-F0-9]{2})", 6));
于 2012-11-27T13:03:25.300 回答
6
string input = "0018103AB839";

var output = string.Join(":", Enumerable.Range(0, 6)
    .Select(i => input.Substring(i * 2, 2)));
于 2012-11-27T13:16:59.280 回答
5

假设我们将 Mac 地址存储在一个 long 中。这是如何将它放在格式化的字符串中:

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);
于 2012-11-27T13:05:01.297 回答