I am trying to convert 4 entered octets of an IP address into their binary form. This is only part of the code for converting the first octet into its 8 bit form. 'oc' is octet - I will fix variable names when I get this working.
remainder = 0
bits = (128,64,32,16,8,4,2,1)
binary = [0,0,0,0,0,0,0,0]
oc = int(input("Enter oc1: "))
if oc > 256:
print("Only 256 or less")
if oc > bits[0] or oc == bits[0]:
binary[0] = 1
remainder = remainder + oc - bits[0]
print(binary)
print(remainder)
elif oc < bits[0]:
binary[0] = 0
print(binary)
if remainder > bits[1] or remainder == bits[1]:
binary[1] = 1
remainder = remainder - bits[1]
print(binary)
print(remainder)
elif oc < bits[1]:
binary[1] = 0
print(binary)
if remainder > bits[2] or oc == bits[2]:
binary[2] = 1
remainder = remainder - bits[2]
print(binary)
print(remainder)
elif oc < bits[2]:
binary[2] = 0
print(binary)
When I enter 128 or greater as the octet I get a successful output.
E.g.: Entering '192' will display '1,1,0,0,0,0,0,0' but anything below 128 and the output is all zeros.
I am sure, I could use a loop for most of this as well but do not know how.