返回
"""
@description:数据进制转换
"""
import pprint
def num_change(number):
return str(number)[2:]
class Change:
def __init__(self, input_string, input_type="s"):
self.string = input_string
self.input_type = input_type
self.num_list = []
def strings(self):
# 传入的是字符时
try:
str_list_dec = [0] * len(self.string)
index = 0
for i in self.string:
str_list_dec[index] = ord(i)
index += 1
str_list_oct = [str(oct(i))[2:] for i in str_list_dec] # 八进制
str_list_bin = [str(bin(i))[2:] for i in str_list_dec] # 二进制
str_list_hex = [str(hex(i))[2:] for i in str_list_dec] # 十六进制
state_message = "转换成功"
return str_list_bin, str_list_oct, str_list_dec, str_list_hex, state_message
except Exception as e:
print(e)
state_message = "转换失败"
return e, state_message
def number(self):
# 处理传入的数字(单个数字)
try:
if self.input_type == "2":
self.num_list = [self.string, num_change(oct(int(self.string, 2))), int(self.string, 2),
num_change(hex(int(self.string, 2)))]
elif self.input_type == "8":
self.num_list = [num_change(bin(int(self.string, 8))), self.string, int(self.string, 8),
num_change(hex(int(self.string, 8)))]
elif self.input_type == "10":
# 十进制需要转为整型
string_10 = int(self.string)
self.num_list = [num_change(bin(string_10)), num_change(oct(string_10)), string_10,
num_change(hex(string_10))]
elif self.input_type == "16":
self.num_list = [num_change(bin(int(self.string, 16))), num_change(oct(int(self.string, 16))),
int(self.string, 16), self.string]
state_message = "转换成功"
return self.num_list, state_message
except Exception as e:
print(e)
state_message = "转换失败"
return e, state_message
def main(self):
try:
if self.input_type == "s":
result = self.strings()
result_dict = {}
for i in range(len(self.string)):
result_dict[self.string[i]] = {
2: result[0][i],
8: result[1][i],
10: result[2][i],
16: result[3][i],
}
state_message = result[-1]
return state_message, result_dict # 返回strings的结果
elif self.input_type in ["2", "8", "10", "16"]:
result = self.number()
result_dict = {self.string: {
2: result[0][0],
8: result[0][1],
10: result[0][2],
16: result[0][3]
}}
state_message = result[-1]
return state_message, result_dict # 返回nums的结果
else:
state_message = ["传输参数错误"]
return state_message
except Exception as e:
print(e)
state_message = ["请选择正确的参数"]
return state_message
# 调用代码
strings = "123"
Change_instance = Change(input_string=strings, input_type="10")
message, *result_date = Change_instance.main()
pprint.pprint(result_date)
print(message)