我搜索了SO尋求幫助,但無法找到我的問題的答案。將子網掩碼「/」符號轉換爲Cisco 0.0.0.0標準
情況:我需要將「/ NN」子網掩碼錶示法(認爲IPTABLES)轉換爲0.0.0.0思科表示法。
NN是子掩碼中「1」的數目,從最低八位位組到最高位。每個八位字節是8位整數。
可能的解決方案:
請32的「0」的一個陣列,並用「1」,則在4個八位字節組填充最後NN數字和轉換爲int ... A/23掩模應該像0.0 .1.255。
我的問題是如何在.NET中做到這一點......我從來沒有使用二進制操作和轉換。
你們可以幫我解決這個問題嗎?
更新 - Stephen已經正確回答!
這裏是代碼移植到.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();
感謝您的回答:D 我會嘗試併發布反饋,但在此之前,我有一個問題。結果將是「255.255」方式還是像cisco一樣的「0.0.1.255」? 此致! – jaderanderson 2010-06-30 19:44:21
這將轉換爲標準的「255.255.128.0」種子網掩碼。如果你需要一個「通配符」掩碼,那麼你可以在調用'HostToNetworkOrder'之前取得結果的位數('〜'),這會給你一個結果如「0.0.1.255」。 – 2010-06-30 19:58:21
謝謝你,會用答案更新代碼!有用! – jaderanderson 2010-07-01 02:51:06