Performing Bitwise Operations on String Variables

93 views Asked by At

Background: I am very new to python and am trying to create a sort of subnetting calculator where the user enters a host's IP address and subnet mask and python calculates and returns the network address for that host.

My issue at this point is performing the bitwise operations on each octet, here is the code thus far:

class Address(object):
#o(number) in my code stands for octet, as in octets 1 through 4 of each address
    def __init__(self,full,o1,o2,o3,o4):
        self.full = full
        self.o1 = o1
        self.o2 = o2
        self.o3 = o3
        self.o4 = o4
#this function's purpose is to split the string input into 4 octets for each address object
def iptobinaryoct(data):
    octet = 1
    o1 = ''
    o2 = ''
    o3 = ''
    o4 = ''
    for x in data.full:
        if x != ".":
            if octet == 1:
                data.o1 += x
            elif octet == 2:
                data.o2 += x
            elif octet == 3:
                data.o3 += x
            elif octet == 4:
                data.o4 += x
        else:
            octet += 1

def nwaddrcalc(ip,snm):
    ipo1 = int(ip.o1)   
    snmo1 = int(snm.o1) 
    nwaddr.o1 = bin(ipo1) & bin(snmo1)
    print ipo1          

ip = Address(raw_input("IP: "),'','','','')
snm = Address(raw_input("SNM: "),'','','','')
nwaddr = Address('','','','','')
iptobinaryoct(ip)
iptobinaryoct(snm)
nwaddrcalc(ip,snm)

The issue is that I cannot treat the variables I am performing bitwise operations on as binary type, python interprets them as strings and is therefore unable to perform any calculation on them, is there a way for me to have these variables interpretted as binary within the nwaddrcalc function?

Many thanks, Phil

1

There are 1 answers

0
samgak On

The bin() function is for converting an integer to a string representation of the binary value, e.g:

print bin(14)

output:

0b1110

In your code, ipo1 and snmo1 are already integers, so you can already perform binary operation on them with no conversion, bin() is not necessary:

def nwaddrcalc(ip,snm):
ipo1 = int(ip.o1)   
snmo1 = int(snm.o1) 
nwaddr.o1 = ipo1 & snmo1
print ipo1