Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Binary 在Python中将数字转换为二进制_Binary_Python 3.x - Fatal编程技术网

Binary 在Python中将数字转换为二进制

Binary 在Python中将数字转换为二进制,binary,python-3.x,Binary,Python 3.x,我试图生成输入值,比如5,并生成该值的二进制版本,同时告诉有多少个1和0。有人知道我该怎么做吗?以及如何对输出进行排序 十进制二进制1 0 5 101 2 1 def begin(): str=0 num = [] while num != -1: num = int(input('Please enter some positive integers. Enter -1 to quit.\n')) if num > 512:

我试图生成输入值,比如5,并生成该值的二进制版本,同时告诉有多少个1和0。有人知道我该怎么做吗?以及如何对输出进行排序

十进制二进制1 0 5 101 2 1

def begin():
    str=0
    num = []

    while num != -1:

        num = int(input('Please enter some positive integers. Enter -1 to quit.\n'))

        if num > 512:
            str += 1
            num-=512
        else:
            str += 0

        if num > 256:
            str += 1
            num-=256
        else:
            str +=0

        if num > 128:
            str += 1
            num-=128
        else:
            str +=0

        if num > 64:
            str += 1
            num-=64
        else:
            str +=0

        if num > 32:
            str += 1
            num-=32
        else:
            str +=0

        if num > 16:
            str += 1
            num-=16
        else:
            str +=0

        if num > 8:
            str += 1
            num-=8
        else:
            str +=0

        if num > 4:
            str += 1
            num-=4
        else:
            str +=0

        if num > 2:
            str += 1
            num-=2
        else:
            str+=0

        if num > 1:
            str += 1
            num-=1
        else:
            str +=0

    print('Decimal Binary\t\tOnes\tZeros')
    print('--------------------------------------')
    num.sort()
    print(num)


begin()
怎么样

n = 5
s = format(n, "b")
print(n, s, s.count("0"), s.count("1"))
用更少的代码以更少的限制方式完成这项工作?

如何

n = 5
s = format(n, "b")
print(n, s, s.count("0"), s.count("1"))

要用更少的代码以更少的限制实现这一点,有一个更简单的表达方式:

>>>垃圾箱(5)
'0b1010'


“bin”可以在python 2.6之后使用,有一个更简单的表达方式:

>>>垃圾箱(5)
'0b1010'


“bin”可以在python 2.6之后使用

从512到1的系列中的数字具有数学关系,您可以在for循环中使用,而不是单独执行每个数字。从512到1的系列中的数字具有数学关系,您可以在for循环中使用,而不是单独执行每个数字。