欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python-八进制、二进制互转换

程序员文章站 2022-07-03 20:42:25
Python-八进制转二进制input_str = input('请输入待转八进制数:')list_num = []list_octal = []lists = []t = 0def octal_binary(): """用于八进制转二进制""" for i in input_str: list_num.append(i) # print(list_num) list_deal = [int(k) for k in list_num]...

Python-八进制转二进制

input_str = input('请输入待转八进制数:')

list_num = []
list_octal = []
lists = []

t = 0


def octal_binary():
    """用于八进制转二进制"""
    for i in input_str:
        list_num.append(i)
    # print(list_num)

    list_deal = [int(k) for k in list_num]
    # print(list_deal)
    list_num.clear()

    for j in list_deal:
        while True:
            if j != 1:
                n = str(j % 2)
                list_octal.append(n)
                j //= 2
            elif j == 1:
                list_octal.append('1')
                list_octal.reverse()
                if len(list_octal) % 3 == 0:
                    pass
                elif len(list_octal) % 3 == 1:
                    list_octal.insert(0, '0')
                    list_octal.insert(1, '0')
                elif len(list_octal) % 3 == 2:
                    list_octal.insert(0, '0')
                lists.extend(list_octal)
                list_octal.clear()
                break

    list_octal.reverse()

    num_str = int(''.join(lists))
    print("该八进制数转化为二进制数为:%d" % num_str)

Python-二进制转八进制

input_str = input('请输入待转二进制数:')
initial_list = []
once_deal_list = []
second_deal_list = []
l_int = len(input_str)
y = 0
r = 2
k = 0


def cut_str():
    """字符串切片"""
    i = 0
    while i < l_int:
        once_deal_list.append(initial_list[i:(i + 3)])
        i += 3


def repair_str():
    """不足3位进行补零"""
    for t in input_str:
        initial_list.append(int(t))

    if input_str.isdecimal():
        print('数字验证通过')
        if l_int % 3 == 0:
            cut_str()
        elif l_int % 3 == 2:
            initial_list.insert(0, 0)
            cut_str()
        else:
            initial_list.insert(0, 0)
            initial_list.insert(1, 0)
            cut_str()
    else:
        print('验证失败请重新输入')
        return


def octonary():
    """转换为八进制"""
    repair_str()
    global k
    global r
    for g in once_deal_list:
        for j in g:
            k += int(j) * 2 ** r
            r -= 1
        second_deal_list.append(k)
        r = 2
        k = 0
    # print('转换成的八进制数为:', end='')
    # for n in second_deal_list:
    #     print(n, end='')
    # print
    end_list = [str(h) for h in second_deal_list]
    end_num = int(''.join(end_list))
    print('转换成的八进制数为:%d' % end_num)


octonary()

本文地址:https://blog.csdn.net/YIGAOYU/article/details/110226748