数据结构实验,利用栈实现二进制,八进制,十进制,十六进制之间的转换,写出完整代码
时间: 2023-12-07 20:04:00 浏览: 97
以下是基于Python语言的栈实现二进制、八进制、十进制、十六进制之间的转换的完整代码:
```
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def size(self):
return len(self.items)
# 十进制转换为二进制
def decimal_to_binary(decimal_num):
binary_stack = Stack()
binary_num = ''
while decimal_num > 0:
remainder = decimal_num % 2
binary_stack.push(remainder)
decimal_num = decimal_num // 2
while not binary_stack.is_empty():
binary_num += str(binary_stack.pop())
return binary_num
# 十进制转换为八进制
def decimal_to_octal(decimal_num):
octal_stack = Stack()
octal_num = ''
while decimal_num > 0:
remainder = decimal_num % 8
octal_stack.push(remainder)
decimal_num = decimal_num // 8
while not octal_stack.is_empty():
octal_num += str(octal_stack.pop())
return octal_num
# 十进制转换为十六进制
def decimal_to_hex(decimal_num):
hex_stack = Stack()
hex_num = ''
while decimal_num > 0:
remainder = decimal_num % 16
if remainder < 10:
hex_stack.push(remainder)
else:
hex_stack.push(chr(ord('A') + remainder - 10))
decimal_num = decimal_num // 16
while not hex_stack.is_empty():
hex_num += str(hex_stack.pop())
return hex_num
# 二进制转换为十进制
def binary_to_decimal(binary_num):
decimal_num = 0
for i in range(len(binary_num)):
decimal_num += int(binary_num[i]) * 2 ** (len(binary_num) - 1 - i)
return decimal_num
# 八进制转换为十进制
def octal_to_decimal(octal_num):
decimal_num = 0
for i in range(len(octal_num)):
decimal_num += int(octal_num[i]) * 8 ** (len(octal_num) - 1 - i)
return decimal_num
# 十六进制转换为十进制
def hex_to_decimal(hex_num):
decimal_num = 0
for i in range(len(hex_num)):
if hex_num[i].isdigit():
decimal_num += int(hex_num[i]) * 16 ** (len(hex_num) - 1 - i)
else:
decimal_num += (ord(hex_num[i].upper()) - ord('A') + 10) * 16 ** (len(hex_num) - 1 - i)
return decimal_num
# 测试
if __name__ == '__main__':
decimal_num = 123
binary_num = decimal_to_binary(decimal_num)
octal_num = decimal_to_octal(decimal_num)
hex_num = decimal_to_hex(decimal_num)
print('十进制数{}对应的二进制数为:{}'.format(decimal_num, binary_num))
print('十进制数{}对应的八进制数为:{}'.format(decimal_num, octal_num))
print('十进制数{}对应的十六进制数为:{}'.format(decimal_num, hex_num))
print('二进制数{}对应的十进制数为:{}'.format(binary_num, binary_to_decimal(binary_num)))
print('八进制数{}对应的十进制数为:{}'.format(octal_num, octal_to_decimal(octal_num)))
print('十六进制数{}对应的十进制数为:{}'.format(hex_num, hex_to_decimal(hex_num)))
```
上述代码中,我们首先定义了一个栈类,然后分别实现了十进制转换为二进制、八进制、十六进制,以及二进制、八进制、十六进制转换为十进制的函数。最后,我们在`if __name__ == '__main__':`语句块中对代码进行了测试,以验证其正确性。
阅读全文