我搜索了 SO 寻求帮助,但找不到我的问题的答案。
情况:我需要将“/NN”子网掩码表示法(想想 IPTABLES)转换为 0.0.0.0 cisco 表示法。
NN 是子掩码中“1”的数量,从最低八位位组到更高位。每个八位字节都是 8 位整数。
可能的解决方案:
制作一个由 32 个“0”组成的数组并用“1”填充最后的 NN 位,然后分组为 4 个八位字节并转换为 int ... /23 掩码应该类似于 0.0.1.255。
我的问题是如何在 .NET 中做到这一点......我从未使用过二进制操作和转换。
你们能帮我解决这个问题吗?
更新 - 斯蒂芬正确回答!
这是移植到 .NET 的代码
if (p.LastIndexOf("/") < 0 ) return p;
int mask= Convert.ToInt32("0"+p.Substring(p.LastIndexOf("/")+1,2));
int zeroBits = 32 - mask; // the number of zero bits
uint result = uint.MaxValue; // all ones
// Shift "cidr" and subtract one to create "cidr" one bits;
// then move them left the number of zero bits.
result &= (uint)((((ulong)0x1 << mascara) - 1) << zeroBits);
result = ~result;
// Note that the result is in host order, so we'd have to convert
// like this before passing to an IPAddress constructor
result = (uint)IPAddress.HostToNetworkOrder((int)result);
string convertedMask = new IPAddress(result).ToString();