问题:在python中将整数转换为二进制

为了将整数转换为二进制,我使用了以下代码:

>>> bin(6)  
'0b110'

什么时候擦除“ 0b”,我用这个:

>>> bin(6)[2:]  
'110'

我能做些什么,如果我想展现600000110,而不是110

In order to convert an integer to a binary, I have used this code :

>>> bin(6)  
'0b110'

and when to erase the ‘0b’, I use this :

>>> bin(6)[2:]  
'110'

What can I do if I want to show 6 as 00000110 instead of 110?


回答 0

>>> '{0:08b}'.format(6)
'00000110'

仅说明格式化字符串的部分:

  • {} 将变量放入字符串
  • 0 将变量放在参数位置0
  • :为该变量添加格式设置选项(否则它将代表小数6
  • 08 将数字格式化为左侧零填充的八位数字
  • b 将数字转换为其二进制表示形式

如果您使用的是Python 3.6或更高版本,则还可以使用f字符串:

>>> f'{6:08b}'
'00000110'
>>> '{0:08b}'.format(6)
'00000110'

Just to explain the parts of the formatting string:

  • {} places a variable into a string
  • 0 takes the variable at argument position 0
  • : adds formatting options for this variable (otherwise it would represent decimal 6)
  • 08 formats the number to eight digits zero-padded on the left
  • b converts the number to its binary representation

If you’re using a version of Python 3.6 or above, you can also use f-strings:

>>> f'{6:08b}'
'00000110'

回答 1

只是另一个想法:

>>> bin(6)[2:].zfill(8)
'00000110'

通过字符串插值Python 3.6+)的更短方法:

>>> f'{6:08b}'
'00000110'

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'

Shorter way via string interpolation (Python 3.6+):

>>> f'{6:08b}'
'00000110'

回答 2

有点纠结的方法…

>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
'00000110'
>>> bin8(-3)
'11111101'

A bit twiddling method…

>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
'00000110'
>>> bin8(-3)
'11111101'

回答 3

只需使用格式功能

format(6, "08b")

一般形式是

format(<the_integer>, "<0><width_of_string><format_specifier>")

Just use the format function

format(6, "08b")

The general form is

format(<the_integer>, "<0><width_of_string><format_specifier>")

回答 4

eumiro的答案更好,但是我只是发布此内容以供参考:

>>> "%08d" % int(bin(6)[2:])
00000110

eumiro’s answer is better, however I’m just posting this for variety:

>>> "%08d" % int(bin(6)[2:])
00000110

回答 5

..或如果不确定该数字始终为8位数字,则可以将其作为参数传递:

>>> '%0*d' % (8, int(bin(6)[2:]))
'00000110'

.. or if you’re not sure it should always be 8 digits, you can pass it as a parameter:

>>> '%0*d' % (8, int(bin(6)[2:]))
'00000110'

回答 6

上老学校总是可行的

def intoBinary(number):
binarynumber=""
if (number!=0):
    while (number>=1):
        if (number %2==0):
            binarynumber=binarynumber+"0"
            number=number/2
        else:
            binarynumber=binarynumber+"1"
            number=(number-1)/2

else:
    binarynumber="0"

return "".join(reversed(binarynumber))

Going Old School always works

def intoBinary(number):
binarynumber=""
if (number!=0):
    while (number>=1):
        if (number %2==0):
            binarynumber=binarynumber+"0"
            number=number/2
        else:
            binarynumber=binarynumber+"1"
            number=(number-1)/2

else:
    binarynumber="0"

return "".join(reversed(binarynumber))

回答 7

numpy.binary_repr(num, width=None) 有一个魔术宽度论点

上面链接的文档中的相关示例:

>>> np.binary_repr(3, width=4)
'0011'

当输入数字为负并且指定了宽度时,将返回二进制补码:

>>> np.binary_repr(-3, width=5)
'11101'

numpy.binary_repr(num, width=None) has a magic width argument

Relevant examples from the documentation linked above:

>>> np.binary_repr(3, width=4)
'0011'

The two’s complement is returned when the input number is negative and width is specified:

>>> np.binary_repr(-3, width=5)
'11101'

回答 8

('0' * 7 + bin(6)[2:])[-8:]

要么

right_side = bin(6)[2:]
'0' * ( 8 - len( right_side )) + right_side
('0' * 7 + bin(6)[2:])[-8:]

or

right_side = bin(6)[2:]
'0' * ( 8 - len( right_side )) + right_side

回答 9

假设您要解析用于表示不总是恒定的变量的位数,一种好方法是使用numpy.binary。

当您将二进制应用于功率集时可能会有用

import numpy as np
np.binary_repr(6, width=8)

Assuming you want to parse the number of digits used to represent from a variable which is not always constant, a good way will be to use numpy.binary.

could be useful when you apply binary to power sets

import numpy as np
np.binary_repr(6, width=8)

回答 10

甚至更简单的方法

my_num = 6
print(f'{my_num:b}')

even an easier way

my_num = 6
print(f'{my_num:b}')

回答 11

最好的方法是指定格式。

format(a, 'b')

以字符串格式返回a的二进制值。

要将二进制字符串转换回整数,请使用int()函数。

int('110', 2)

返回二进制字符串的整数值。

The best way is to specify the format.

format(a, 'b')

returns the binary value of a in string format.

To convert a binary string back to integer, use int() function.

int('110', 2)

returns integer value of binary string.


回答 12

def int_to_bin(num, fill):
    bin_result = ''

    def int_to_binary(number):
        nonlocal bin_result
        if number > 1:
            int_to_binary(number // 2)
        bin_result = bin_result + str(number % 2)

    int_to_binary(num)
    return bin_result.zfill(fill)
def int_to_bin(num, fill):
    bin_result = ''

    def int_to_binary(number):
        nonlocal bin_result
        if number > 1:
            int_to_binary(number // 2)
        bin_result = bin_result + str(number % 2)

    int_to_binary(num)
    return bin_result.zfill(fill)

回答 13

您可以使用:

"{0:b}".format(n)

我认为这是最简单的方法!

You can use just:

"{0:b}".format(n)

In my opinion this is the easiest way!


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。