Tell me how to get a value equal to FFFFFFFE
it turns out to output only EFFFF
in reverse order and without the first two characters of FF
Source Code: Converting subnet mask “/” notation to Cisco 0.0.0.0 standard
var cidr = 23;
var zeroBits = 32 - cidr;
var result = uint.MaxValue;
result &= (uint)((((ulong)0x1 << cidr) - 1) << zeroBits);
result = (uint)IPAddress.HostToNetworkOrder((int)result);
textBoxHex.Text = result.ToString("X");
One possible solution, using the BitVector32 class to create the bit array from the length in bits of the net mask.
The bit mask returned by BitVector32
would be enough, if you just want to print the Hex representation.
Let's assume you also want to represent the address in IPV4
format. In this case, the net mask is of course inverted. To convert it to a valid IpAddress
, we need to invert the bytes order.
IPAddress.HostToNetworkOrder
won't directly convert to network byte order the value returned by the BitVector32.Data
property.
We can use BitConverter.GetBytes and Array.Reverse()
or LINQ's .Reverse()
method to do the same thing.
This is all that's needed:
int cidr = 23;
var bits = new BitVector32(-1 << (32 - cidr));
To return the HEX representation of the bit mask, just convert it to string specifying the Hex format:
Formatting Types in .NET (MSDN)
Console.WriteLine(bits.Data.ToString("X2"));
=> FFFFFE00
To transform it into an IpAddress
format, if needed:
var bytes = BitConverter.GetBytes((uint)bits.Data);
var netMask = new IPAddress(bytes.Reverse().ToArray());
Console.WriteLine(netMask);
=> 255.255.254.0