Demo entry 6754857

basic

   

Submitted by anonymous on Jul 23, 2018 at 02:26
Language: Python. Code size: 2.4 kB.

def convert_to_base2(base_10_ip):
	base_10_ip_split_list = base_10_ip.split('.')
	rem = ''
	base_2_ip_list = []
	rem_str = ''
	for each_octet in base_10_ip_split_list:
		each_octet = int(each_octet)
		if each_octet == 0:
			rem_str = '00000000'		
		while(each_octet > 0):
			rem = each_octet % 2
			rem_str = rem_str + str(rem)
			each_octet = each_octet // 2
		rem_str = rem_str[::-1]
		rem_str = rem_str.zfill(8)
		base_2_ip_list.append(rem_str)
		rem_str = ''
	base_2_ip = '.'.join(base_2_ip_list)
	return base_2_ip


def convert_to_base10(base_2_ip):
	base_2_ip_split_list = base_2_ip.split('.')
	base_10_octet = 0
	base_10_ip_list = []
	base_10_ip = ''
	num = 0

	for each_octet in base_2_ip_split_list:
		for index  in range(len(each_octet) -1,-1,-1):
			base_10_octet = base_10_octet + int(each_octet[index]) * 2 ** num
			num += 1
		base_10_ip_list.append(str(base_10_octet))
		base_10_octet = 0
		num = 0
	base_10_ip = '.'.join(base_10_ip_list)
	return base_10_ip

	
base_2_ip_print = convert_to_base2('192.2.3.255')
base_10_ip_print = convert_to_base10('11000000.00000010.00000011.11111111')

print(base_2_ip_print)
print(base_10_ip_print)

def convert_to_base2_v0(base_10_ip):
	base_10_ip = base_10_ip.split('.')
	base_2_ip_list = []
	for octet in base_10_ip:
		octet_base2 = bin(int(octet))
		octet_base2 = octet_base2[2:]
		octet_base2 = octet_base2.zfill(8)
		base_2_ip_list.append(octet_base2)
		base_2_ip_str = '.'.join(base_2_ip_list)
	return base_2_ip_str


base_2_ip_print_v0 = convert_to_base2_v0('192.2.3.255')
print(base_2_ip_print_v0)

def convert_to_base10_v0(base_2_ip):
	base_2_ip = base_2_ip.split('.')
	print(base_2_ip)
	base_10_ip_list = []

	for octet in base_2_ip:
		octet_base10 = int(octet,2)
		base_10_ip_list.append(str(octet_base10))
	return '.'.join(base_10_ip_list)


base_10_ip_print_v0 = convert_to_base10_v0('11000000.00000010.00000011.11111111')
print(base_10_ip_print_v0)

def is_valid_ip(ip_address):
	is_valid = False	
	ip = ip_address.split('.')

	if len(ip) != 4:
		return False

	if int(ip[0]) <= 0:
		return False

	for octet in ip:
		octet = int(octet)

		if octet < 0 or octet > 255:
			is_valid = False
			return is_valid
		else: 
			is_valid = True
			continue
	return is_valid

print(is_valid_ip('1.1.256.0'))

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).