I have to calculate the IPv4 subnet address which can be achieved by adding the IP address binary to the subnet mask binary. I can convert them both to binary with this code
Public Function Dec2Bin(ByVal DeciValue As Long, Optional ByVal NoOfBits As Integer = 8) _
As String
Dim i As Integer
Do While DeciValue > (2 ^ NoOfBits) - 1
NoOfBits = NoOfBits + 8
Loop
Dec2Bin = vbNullString
For i = 0 To (NoOfBits - 1)
Dec2Bin = CStr((DeciValue And 2 ^ i) / 2 ^ i) & Dec2Bin
Next i
End Function
But now how do I add the two 32-bit strings together in order to get the subnet adress? I also have the dec-to-bin function, so I don't need any help with that.
So, I suspect DeciValue
is your IP address in 32-bit numeric representation and NoOfBits
is the number of bits in the subnet mask (as 8 for 255.0.0.0, 16 for 255.255.0.0 and 24 for 255.255.255.0 etc).
What you can do is this:
Public Function Network_Address(IP as UInteger, Optional Mask as UInteger = 0)
If Mask = 0 Then
Mask = 8 * ((IP >> 30) + 1)
End If
Network_Address = IP And (4294967295 Xor ((2 ^ (32 - Mask)) - 1))
End Function
Now you have the network address as its numeric representation. I suspect thats what you want.
This function will also detect the IP subnet mask size automatically if none is specified.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.