''' 整数转换成二进制 ''' def bin_ary(number): if not number.isdigit(): print('enter your number') else: number = int(number) s = '' while(number // 2 >= 1): remainder = number % 2 #余数 quotient = number // 2 #商数 s = str(remainder) + s number = quotient print('number:', number) s = str(number) + s return s ''' 二进制转换成数值 ''' def int_ary(number): number_len = len(number) sum = 0 for i in range(number_len): sum = sum + (2**i) * int(number[number_len - 1 - i]) return sum ''' ip转换成整数 ''' def ip_change_digit(ip): strs = ip.split('.') ip_strs = '' for i in strs: result = bin_ary(i) result_len = len(result) if result_len > 8: print('your ip is error') elif result_len < 8: for i in range(8 - result_len): result = str(0) + result print(result) ip_strs = ip_strs + result return int_ary(ip_strs) ''' 整数转换成ip ''' def digit_change_ip(digit): s = bin_ary(digit) print(s) ip_len = len(s) if ip_len > 32: print('your number is error') elif ip_len <= 32: for i in range(32 - ip_len): s = str(0) + s li = [] li.append(s[0:8]) li.append(s[8:16]) li.append(s[16:24]) li.append(s[24:32]) print(li) for i in range(len(li)): li[i] = str(int_ary(li[i])) result = ('.').join(li) return result if __name__ == '__main__': print(digit_change_ip(str(ip_change_digit('1270.101.101.11'))))