ANDing 2 Binary Values (Subnetting)

Frappz

New Member
Licensed User
Longtime User
Hello,
I'm currently writing a subnet calculator (For educational purpose, My professor will kill me if he finds out we get anywhere near a subnet calc) and I'm having a bit of a problem on the ANDing of 2 binary values. I'm trying to determine if the IP entered is a host IP or not, and if it is identified as a host IP, I want it to identify its network IP by doing the ANDing method with 2 binary value:
e.g.
IP: 192.34.45.2 (Identified as HOST)
Mask: 255.255.255.0

ANDing
11000000.00100010.00101101.00000010
11111111.11111111.11111111.00000000
-----------------------------------------------
11000000.00100010.00101101.00000000 = Net ID: 192.34.45.0

However, when I do a Bit.And(Val1, Val2), it returns large values that are far off from what I want

B4X:
dotA = txtIP.Text.IndexOf2(".", 0)
For i = 0 To dotA - 1 
     valA = valA & txtIP.Text.CharAt(i)
Next

IPa = valA

If IsHost = True then
dotA1 = txtMask.Text.IndexOf2(".", 0)
For i = 0 To dotA1 - 1
     maskA = maskA & txtMask.Text.CharAt(i)
Next

MaskIPa = maskA

' Tried inserting codes to convert the IP values to binary first but still gives me godly amount of value

NetIP = Bit.And(IPa, MaskIPa)
Log(NetIP)
End If

NetIP returns: 98946

I'm sorry if my codes are messy and forgive me for the Subnetting explanation at the start, I'm sure everyone knows subnetting better than me, but just a reference for those who doesn't :confused:

Thank you
 
Last edited:

DKCERT

Member
Licensed User
Longtime User
You wil need to do it octet by octet:

Oct1 = Bit.And(192, 255)
Oct2 = Bit.And(34, 255)
Oct3 = Bit.And(45, 255)
Oct4 = Bit.And(2, 0)

NetId = Oct1 & "." & Oct2 & "." & Oct3 & "." & Oct4
 
Last edited:
Upvote 0

Frappz

New Member
Licensed User
Longtime User
Sorry if I was unclear, I posted just a part of my code, I am doing it octet by octet, I think I just figured out how though thanks to your respond DK,

I had the octet values converted as Bit.ToBinaryString(IPa) when they should have just been left as integer values.
Thank you DKCERT, working well now.
 
Upvote 0
Top