Лабораторная работа - Системы счисления

This commit is contained in:
Dmitriy Shishkov 2020-04-07 22:15:43 +05:00
parent cb9bab6253
commit f36936ac9d

20
1.py
View File

@ -1,58 +1,68 @@
dictionary = [chr(i) for i in range(ord('0'), ord('9')+1)] + \ dictionary = [chr(i) for i in range(ord('0'), ord('9')+1)] + \
[chr(i) for i in range(ord('A'), ord('F')+1)] [chr(i) for i in range(ord('A'), ord('F')+1)]
def validation(string, ibase, tbase): def validation(string, ibase, tbase):
for n in string: for n in string:
if not n in dictionary[:ibase] + [',', '.']: if not n in dictionary[:ibase] + [',', '.']:
return False return False
if ibase < 2 or ibase > 16 or tbase < 2 or tbase > 16: if ibase < 2 or ibase > 16 or tbase < 2 or tbase > 16:
return False return False
return True
return True
def convert(string, ibase, tbase): def convert(string, ibase, tbase):
if string == '0': if string == '0':
return 0 return 0
if ibase != 10: if ibase != 10:
string = other_to_dec(string, ibase) string = other_to_dec(string, ibase)
if tbase == 10: if tbase == 10:
return string return string
string = float(string) string = float(string)
integer = dec_to_other(int(string), tbase) integer = dec_to_other(int(string), tbase)
decimal = string - int(string) decimal = string - int(string)
if decimal: if decimal:
decimal = float_dec_with__to_other(decimal, tbase) decimal = float_dec_with__to_other(decimal, tbase)
return integer + ',' + decimal return integer + ',' + decimal
return integer return integer
def other_to_dec(string, ibase): def other_to_dec(string, ibase):
sum = 0 sum = 0
amount = len(string.split('.')[0])-1 amount = len(string.split('.')[0])-1
for n in string: for n in string:
if n != '.': if n != '.':
sum += int(dictionary.index(n)) * ibase**amount sum += int(dictionary.index(n)) * ibase**amount
amount -= 1 amount -= 1
return sum
return sum
def dec_to_other(num, tbase): def dec_to_other(num, tbase):
result = '' result = ''
while num // tbase > 0: while num // tbase > 0:
result += str(dictionary[int(num % tbase)]) result += str(dictionary[int(num % tbase)])
num //= tbase num //= tbase
result += str(dictionary[int(num % tbase)])
return result[::-1]
result += str(dictionary[int(num % tbase)])
return result[::-1]
def float_dec_with__to_other(num, tbase): def float_dec_with__to_other(num, tbase):
result = '' result = ''
counter = 0 counter = 0
while num - int(num) > 0 and counter < 8: while num - int(num) > 0 and counter < 8:
result += str(dictionary[int(num * tbase)]) result += str(dictionary[int(num * tbase)])
num = num * tbase - int(num * tbase) num = num * tbase - int(num * tbase)
counter += 1 counter += 1
return result[:7] return result[:7]
# _____ MAIN PROGRAMM _____ # _____ MAIN PROGRAMM _____