Md-Abdul-Halim-Rafi

Number System Conversion

Mar 16th, 2022
978
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. # consts
  2. BASES = [2, 8, 10, 16];
  3.  
  4. def convert(num, base):
  5.     # create a list to store the converted number
  6.     converted_num = [];
  7.     # create a list to store the digits
  8.     digits = "0123456789ABCDEF";
  9.     # convert the number to the base
  10.     while num > 0:
  11.         converted_num.append(digits[num % base]);
  12.         num = num // base;
  13.     # reverse the list
  14.     converted_num.reverse();
  15.     # join the list
  16.     return "".join(converted_num);
  17.  
  18. # check if any number is in binary form in a function
  19. def check_valid_form(num, base):
  20.  
  21.     # create a list to store the digits
  22.     digits = "01";
  23.    
  24.     if base == 8:
  25.         digits = "01234567";
  26.     elif base == 10:
  27.         digits = "0123456789";
  28.     elif base == 16:
  29.         digits = "0123456789ABCDEF";
  30.  
  31.     # check the number to the base
  32.     for digit in str(num):
  33.         if digit not in digits:
  34.             return False;
  35.     return True;
  36.  
  37. nums = [];
  38. bases = [];
  39. total_nums = 0;
  40.  
  41. # continue taking inputs until the user enters "Stop"
  42. while True:
  43.  
  44.     # get the number and the base with space to convert
  45.     num_base = input("Enter a number and a base to convert it to decimal (or 'Stop' to quit): \n");
  46.  
  47.     # if the user enters "Stop"
  48.     if num_base.lower() == "stop":
  49.         break;
  50.  
  51.     num_base_map = num_base.split();
  52.  
  53.     if len(num_base_map) == 0:
  54.         print("\nInvalid input\n");
  55.         continue;
  56.     elif len(num_base_map) == 1:
  57.         print("\nInvalid base\n");
  58.         continue;
  59.  
  60.     nums.append(num_base_map[0]);
  61.     bases.append(num_base_map[1]);
  62.     total_nums += 1;
  63.  
  64. # check if the base is valid
  65. for i in range(total_nums):
  66.  
  67.     input_num = int(nums[i]);
  68.     input_base = int(bases[i]);
  69.  
  70.     print("\nFor number {0} with base {1}:\n".format(input_num, input_base));
  71.  
  72.     if not input_base or input_base not in BASES or not check_valid_form(input_num, input_base):
  73.         print("Invalid base: " + str(input_base));
  74.         continue;
  75.  
  76.     for base in BASES:
  77.  
  78.         if base == input_base:
  79.             continue;
  80.  
  81.         print(str(convert(input_num, base)) + " if base is " + str(base));
Advertisement
Add Comment
Please, Sign In to add comment