问题:Python int转换为二进制字符串?

是否有任何固定的Python方法将Python中的Integer(或Long)转换为二进制字符串?

Google上有无数的dec2bin()函数…但是我希望可以使用内置函数/库。

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google… But I was hoping I could use a built-in function / library.


回答 0

Python的字符串格式方法可以采用格式规范。

>>> "{0:b}".format(37)
'100101'

适用于Python 2的格式规范文档

适用于Python 3的格式规范文档

Python’s string format method can take a format spec.

>>> "{0:b}".format(37)
'100101'

Format spec docs for Python 2

Format spec docs for Python 3


回答 1

如果您正在寻找等同于hex(),它是在python 2.6中添加的。

例:

>>> bin(10)
'0b1010'

If you’re looking for as an equivalent to hex(), it was added in python 2.6.

Example:

>>> bin(10)
'0b1010'

回答 2

Python的实际确实已经内建了对这个东西,做如操作的能力'{0:b}'.format(42),这将给你的位模式(在一个字符串)42,或101010


对于更一般的哲学,没有语言或库会向用户群提供他们想要的一切。如果您所处的环境不能完全满足您的需求,则在开发过程中应收集代码片段,以确保您不必重复编写同一件事。例如伪代码:

define intToBinString, receiving intVal:
    if intVal is equal to zero:
        return "0"
    set strVal to ""
    while intVal is greater than zero:
        if intVal is odd:
            prefix "1" to strVal
        else:
            prefix "0" to strVal
        divide intVal by two, rounding down
    return strVal

它将根据十进制值构造您的二进制字符串。请记住,这是伪代码的通用位,虽然这可能不是有效的方式,但是您似乎建议进行迭代,但这并没有太大的区别。它实际上只是作为如何完成操作的指南。

总体思路是使用代码(按优先顺序排列):

  • 语言或内置库。
  • 具有适当许可证的第三方库。
  • 你自己的收藏。
  • 您需要编写一些新内容(并保存在自己的收藏夹中以备后用)。

Python actually does have something already built in for this, the ability to do operations such as '{0:b}'.format(42), which will give you the bit pattern (in a string) for 42, or 101010.


For a more general philosophy, no language or library will give its user base everything that they desire. If you’re working in an environment that doesn’t provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example, the pseudo-code:

define intToBinString, receiving intVal:
    if intVal is equal to zero:
        return "0"
    set strVal to ""
    while intVal is greater than zero:
        if intVal is odd:
            prefix "1" to strVal
        else:
            prefix "0" to strVal
        divide intVal by two, rounding down
    return strVal

which will construct your binary string based on the decimal value. Just keep in mind that’s a generic bit of pseudo-code which may not be the most efficient way of doing it though, with the iterations you seem to be proposing, it won’t make much difference. It’s really just meant as a guideline on how it could be done.

The general idea is to use code from (in order of preference):

  • the language or built-in libraries.
  • third-party libraries with suitable licenses.
  • your own collection.
  • something new you need to write (and save in your own collection for later).

回答 3

如果要使用不带0b前缀的文本表示形式,则可以使用以下代码:

get_bin = lambda x: format(x, 'b')

print(get_bin(3))
>>> '11'

print(get_bin(-3))
>>> '-11'

当您需要n位表示形式时:

get_bin = lambda x, n: format(x, 'b').zfill(n)
>>> get_bin(12, 32)
'00000000000000000000000000001100'
>>> get_bin(-12, 32)
'-00000000000000000000000000001100'

或者,如果您更喜欢具有以下功能:

def get_bin(x, n=0):
    """
    Get the binary representation of x.

    Parameters
    ----------
    x : int
    n : int
        Minimum number of digits. If x needs less digits in binary, the rest
        is filled with zeros.

    Returns
    -------
    str
    """
    return format(x, 'b').zfill(n)

If you want a textual representation without the 0b-prefix, you could use this:

get_bin = lambda x: format(x, 'b')

print(get_bin(3))
>>> '11'

print(get_bin(-3))
>>> '-11'

When you want a n-bit representation:

get_bin = lambda x, n: format(x, 'b').zfill(n)
>>> get_bin(12, 32)
'00000000000000000000000000001100'
>>> get_bin(-12, 32)
'-00000000000000000000000000001100'

Alternatively, if you prefer having a function:

def get_bin(x, n=0):
    """
    Get the binary representation of x.

    Parameters
    ----------
    x : int
    n : int
        Minimum number of digits. If x needs less digits in binary, the rest
        is filled with zeros.

    Returns
    -------
    str
    """
    return format(x, 'b').zfill(n)

回答 4

作为参考:

def toBinary(n):
    return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])

此函数可以转换一个大的正整数18446744073709551615,以string表示'1111111111111111111111111111111111111111111111111111111111111111'

可以修改它以使用更大的整数,尽管它可能不如"{0:b}".format()或方便bin()

As a reference:

def toBinary(n):
    return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])

This function can convert a positive integer as large as 18446744073709551615, represented as string '1111111111111111111111111111111111111111111111111111111111111111'.

It can be modified to serve a much larger integer, though it may not be as handy as "{0:b}".format() or bin().


回答 5

一种简单的方法是使用字符串格式,请参见本页

>> "{0:b}".format(10)
'1010'

如果要固定长度的二进制字符串,则可以使用以下命令:

>> "{0:{fill}8b}".format(10, fill='0')
'00001010'

如果需要二进制补码,则可以使用以下行:

'{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n)

其中n是二进制字符串的宽度。

A simple way to do that is to use string format, see this page.

>> "{0:b}".format(10)
'1010'

And if you want to have a fixed length of the binary string, you can use this:

>> "{0:{fill}8b}".format(10, fill='0')
'00001010'

If two’s complement is required, then the following line can be used:

'{0:{fill}{width}b}'.format((x + 2**n) % 2**n, fill='0', width=n)

where n is the width of the binary string.


回答 6

这是针对python 3的,它保持前导零!

print(format(0, '08b'))

在此处输入图片说明

This is for python 3 and it keeps the leading zeros !

print(format(0, '08b'))

enter image description here


回答 7

lambda的单线

>>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)

测试:

>>> binary(5)
'101'



编辑

但是之后 :(

t1 = time()
for i in range(1000000):
     binary(i)
t2 = time()
print(t2 - t1)
# 6.57236599922

相较于

t1 = time()
for i in range(1000000):
    '{0:b}'.format(i)
t2 = time()
print(t2 - t1)
# 0.68017411232

one-liner with lambda:

>>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)

test:

>>> binary(5)
'101'



EDIT:

but then :(

t1 = time()
for i in range(1000000):
     binary(i)
t2 = time()
print(t2 - t1)
# 6.57236599922

in compare to

t1 = time()
for i in range(1000000):
    '{0:b}'.format(i)
t2 = time()
print(t2 - t1)
# 0.68017411232

回答 8

替代方案摘要:

n=42
assert  "-101010" == format(-n, 'b')
assert  "-101010" == "{0:b}".format(-n)
assert  "-101010" == (lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:])(-n)
assert "0b101010" == bin(n)
assert   "101010" == bin(n)[2:]   # But this won't work for negative numbers.

贡献者包括John FouhyTung NguyenmVChrMartin Thoma。和马丁·彼得斯(Martijn Pieters)。

Summary of alternatives:

n=42
assert  "-101010" == format(-n, 'b')
assert  "-101010" == "{0:b}".format(-n)
assert  "-101010" == (lambda x: x >= 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:])(-n)
assert "0b101010" == bin(n)
assert   "101010" == bin(n)[2:]   # But this won't work for negative numbers.

Contributors include John Fouhy, Tung Nguyen, mVChr, Martin Thoma. and Martijn Pieters.


回答 9

由于前面的答案大多使用format(),因此这是f字符串实现。

integer = 7
bit_count = 5
print(f'{integer:0{bit_count}b}')

输出:

00111

为方便起见,这里是格式化字符串文字的python docs链接:https : //docs.python.org/3/reference/lexical_analysis.html#f-strings

As the preceding answers mostly used format(), here is an f-string implementation.

integer = 7
bit_count = 5
print(f'{integer:0{bit_count}b}')

Output:

00111

For convenience here is the python docs link for formatted string literals: https://docs.python.org/3/reference/lexical_analysis.html#f-strings.


回答 10

>>> format(123, 'b')
'1111011'
>>> format(123, 'b')
'1111011'

回答 11

使用numpy pack / unpackbits,它们是您最好的朋友。

Examples
--------
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
       [ 7],
       [23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)

Using numpy pack/unpackbits, they are your best friends.

Examples
--------
>>> a = np.array([[2], [7], [23]], dtype=np.uint8)
>>> a
array([[ 2],
       [ 7],
       [23]], dtype=uint8)
>>> b = np.unpackbits(a, axis=1)
>>> b
array([[0, 0, 0, 0, 0, 0, 1, 0],
       [0, 0, 0, 0, 0, 1, 1, 1],
       [0, 0, 0, 1, 0, 1, 1, 1]], dtype=uint8)

回答 12

对于我们这些需要将带符号整数(范围-2 **(digits-1)到2 **(digits-1)-1)转换为2的补码二进制字符串的人来说,这可行:

def int2bin(integer, digits):
if integer >= 0:
    return bin(integer)[2:].zfill(digits)
else:
    return bin(2**digits + integer)[2:]

这将生成:

>>> int2bin(10, 8)
'00001010'
>>> int2bin(-10, 8)
'11110110'
>>> int2bin(-128, 8)
'10000000'
>>> int2bin(127, 8)
'01111111'

For those of us who need to convert signed integers (range -2**(digits-1) to 2**(digits-1)-1) to 2’s complement binary strings, this works:

def int2bin(integer, digits):
if integer >= 0:
    return bin(integer)[2:].zfill(digits)
else:
    return bin(2**digits + integer)[2:]

This produces:

>>> int2bin(10, 8)
'00001010'
>>> int2bin(-10, 8)
'11110110'
>>> int2bin(-128, 8)
'10000000'
>>> int2bin(127, 8)
'01111111'

回答 13

除非我误解了二进制字符串的含义,否则我认为您要查找的模块是struct

Unless I’m misunderstanding what you mean by binary string I think the module you are looking for is struct


回答 14

通过使用按位运算符,使用另一种算法的另一种解决方案。

def int2bin(val):
    res=''
    while val>0:
        res += str(val&1)
        val=val>>1     # val=val/2 
    return res[::-1]   # reverse the string

更快的版本而无需反转字符串。

def int2bin(val):
   res=''
   while val>0:
       res = chr((val&1) + 0x30) + res
       val=val>>1    
   return res 

Yet another solution with another algorithm, by using bitwise operators.

def int2bin(val):
    res=''
    while val>0:
        res += str(val&1)
        val=val>>1     # val=val/2 
    return res[::-1]   # reverse the string

A faster version without reversing the string.

def int2bin(val):
   res=''
   while val>0:
       res = chr((val&1) + 0x30) + res
       val=val>>1    
   return res 

回答 15

def binary(decimal) :
    otherBase = ""
    while decimal != 0 :
        otherBase  =  str(decimal % 2) + otherBase
        decimal    //=  2
    return otherBase

print binary(10)

输出:

1010

def binary(decimal) :
    otherBase = ""
    while decimal != 0 :
        otherBase  =  str(decimal % 2) + otherBase
        decimal    //=  2
    return otherBase

print binary(10)

output:

1010


回答 16

你可以这样:

bin(10)[2:]

要么 :

f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c

you can do like that :

bin(10)[2:]

or :

f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c

回答 17

这是我刚刚实现的代码。这不是一种方法,但是您可以将其用作现成的功能

def inttobinary(number):
  if number == 0:
    return str(0)
  result =""
  while (number != 0):
      remainder = number%2
      number = number/2
      result += str(remainder)
  return result[::-1] # to invert the string

Here is the code I’ve just implemented. This is not a method but you can use it as a ready-to-use function!

def inttobinary(number):
  if number == 0:
    return str(0)
  result =""
  while (number != 0):
      remainder = number%2
      number = number/2
      result += str(remainder)
  return result[::-1] # to invert the string

回答 18

这是使用divmod()功能的简单解决方案,该功能返回提醒和不带分数的除法结果。

def dectobin(number):
    bin = ''
    while (number >= 1):
        number, rem = divmod(number, 2)
        bin = bin + str(rem)
    return bin

here is simple solution using the divmod() fucntion which returns the reminder and the result of a division without the fraction.

def dectobin(number):
    bin = ''
    while (number >= 1):
        number, rem = divmod(number, 2)
        bin = bin + str(rem)
    return bin

回答 19

n=input()
print(bin(n).replace("0b", ""))
n=input()
print(bin(n).replace("0b", ""))

回答 20

numpy.binary_repr(num, width=None)

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

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

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

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

numpy.binary_repr(num, width=None)

Examples from the documentation link above:

>>> np.binary_repr(3)
'11'
>>> np.binary_repr(-3)
'-11'
>>> 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=3)
'101'
>>> np.binary_repr(-3, width=5)
'11101'

回答 21

有点类似的解决方案

def to_bin(dec):
    flag = True
    bin_str = ''
    while flag:
        remainder = dec % 2
        quotient = dec / 2
        if quotient == 0:
            flag = False
        bin_str += str(remainder)
        dec = quotient
    bin_str = bin_str[::-1] # reverse the string
    return bin_str 

Somewhat similar solution

def to_bin(dec):
    flag = True
    bin_str = ''
    while flag:
        remainder = dec % 2
        quotient = dec / 2
        if quotient == 0:
            flag = False
        bin_str += str(remainder)
        dec = quotient
    bin_str = bin_str[::-1] # reverse the string
    return bin_str 

回答 22

这是使用常规数学的另一种方式,没有循环,只有递归。(特殊情况0不返回任何内容)。

def toBin(num):
  if num == 0:
    return ""
  return toBin(num//2) + str(num%2)

print ([(toBin(i)) for i in range(10)])

['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']

Here’s yet another way using regular math, no loops, only recursion. (Trivial case 0 returns nothing).

def toBin(num):
  if num == 0:
    return ""
  return toBin(num//2) + str(num%2)

print ([(toBin(i)) for i in range(10)])

['', '1', '10', '11', '100', '101', '110', '111', '1000', '1001']

回答 23

计算器,具有DEC,BIN,HEX的所有必要功能:(使用Python 3.5进行制造和测试)

您可以更改输入的测试编号并获得转换后的编号。

# CONVERTER: DEC / BIN / HEX

def dec2bin(d):
    # dec -> bin
    b = bin(d)
    return b

def dec2hex(d):
    # dec -> hex
    h = hex(d)
    return h

def bin2dec(b):
    # bin -> dec
    bin_numb="{0:b}".format(b)
    d = eval(bin_numb)
    return d,bin_numb

def bin2hex(b):
    # bin -> hex
    h = hex(b)
    return h

def hex2dec(h):
    # hex -> dec
    d = int(h)
    return d

def hex2bin(h):
    # hex -> bin
    b = bin(h)
    return b


## TESTING NUMBERS
numb_dec = 99
numb_bin = 0b0111 
numb_hex = 0xFF


## CALCULATIONS
res_dec2bin = dec2bin(numb_dec)
res_dec2hex = dec2hex(numb_dec)

res_bin2dec,bin_numb = bin2dec(numb_bin)
res_bin2hex = bin2hex(numb_bin)

res_hex2dec = hex2dec(numb_hex)
res_hex2bin = hex2bin(numb_hex)



## PRINTING
print('------- DECIMAL to BIN / HEX -------\n')
print('decimal:',numb_dec,'\nbin:    ',res_dec2bin,'\nhex:    ',res_dec2hex,'\n')

print('------- BINARY to DEC / HEX -------\n')
print('binary: ',bin_numb,'\ndec:    ',numb_bin,'\nhex:    ',res_bin2hex,'\n')

print('----- HEXADECIMAL to BIN / HEX -----\n')
print('hexadec:',hex(numb_hex),'\nbin:    ',res_hex2bin,'\ndec:    ',res_hex2dec,'\n')

Calculator with all neccessary functions for DEC,BIN,HEX: (made and tested with Python 3.5)

You can change the input test numbers and get the converted ones.

# CONVERTER: DEC / BIN / HEX

def dec2bin(d):
    # dec -> bin
    b = bin(d)
    return b

def dec2hex(d):
    # dec -> hex
    h = hex(d)
    return h

def bin2dec(b):
    # bin -> dec
    bin_numb="{0:b}".format(b)
    d = eval(bin_numb)
    return d,bin_numb

def bin2hex(b):
    # bin -> hex
    h = hex(b)
    return h

def hex2dec(h):
    # hex -> dec
    d = int(h)
    return d

def hex2bin(h):
    # hex -> bin
    b = bin(h)
    return b


## TESTING NUMBERS
numb_dec = 99
numb_bin = 0b0111 
numb_hex = 0xFF


## CALCULATIONS
res_dec2bin = dec2bin(numb_dec)
res_dec2hex = dec2hex(numb_dec)

res_bin2dec,bin_numb = bin2dec(numb_bin)
res_bin2hex = bin2hex(numb_bin)

res_hex2dec = hex2dec(numb_hex)
res_hex2bin = hex2bin(numb_hex)



## PRINTING
print('------- DECIMAL to BIN / HEX -------\n')
print('decimal:',numb_dec,'\nbin:    ',res_dec2bin,'\nhex:    ',res_dec2hex,'\n')

print('------- BINARY to DEC / HEX -------\n')
print('binary: ',bin_numb,'\ndec:    ',numb_bin,'\nhex:    ',res_bin2hex,'\n')

print('----- HEXADECIMAL to BIN / HEX -----\n')
print('hexadec:',hex(numb_hex),'\nbin:    ',res_hex2bin,'\ndec:    ',res_hex2dec,'\n')

回答 24

要计算数字的二进制数:

print("Binary is {0:>08b}".format(16))

要计算数字的十六进制十进制

print("Hexa Decimal is {0:>0x}".format(15))

要计算所有二进制数,直到16 ::

for i in range(17):
   print("{0:>2}: binary is {0:>08b}".format(i))

计算十六进制小数,直到17

 for i in range(17):
    print("{0:>2}: Hexa Decimal is {0:>0x}".format(i))
##as 2 digit is enogh for hexa decimal representation of a number

To calculate binary of numbers:

print("Binary is {0:>08b}".format(16))

To calculate the Hexa decimal of a number:

print("Hexa Decimal is {0:>0x}".format(15))

To Calculate all the binary no till 16::

for i in range(17):
   print("{0:>2}: binary is {0:>08b}".format(i))

To calculate Hexa decimal no till 17

 for i in range(17):
    print("{0:>2}: Hexa Decimal is {0:>0x}".format(i))
##as 2 digit is enogh for hexa decimal representation of a number

回答 25

如果你愿意放弃“纯” Python的,但收获了很多火力,有贤者这里的例子

sage: a = 15
sage: a.binary()
'1111'

您会注意到它以字符串形式返回,因此要将其用作数字,您需要执行以下操作

sage: eval('0b'+b)
15

If you are willing to give up “pure” Python but gain a lot of firepower, there is Sageexample here:

sage: a = 15
sage: a.binary()
'1111'

You’ll note that it returns as a string, so to use it as a number you’d want to do something like

sage: eval('0b'+b)
15

回答 26

try:
    while True:
        p = ""
        a = input()
        while a != 0:
            l = a % 2
            b = a - l
            a = b / 2
            p = str(l) + p
        print(p)
except:
    print ("write 1 number")
try:
    while True:
        p = ""
        a = input()
        while a != 0:
            l = a % 2
            b = a - l
            a = b / 2
            p = str(l) + p
        print(p)
except:
    print ("write 1 number")

回答 27

我发现了一种使用矩阵运算将十进制转换为二进制的方法。

import numpy as np
E_mat = np.tile(E,[1,M])
M_order = pow(2,(M-1-np.array(range(M)))).T
bindata = np.remainder(np.floor(E_mat /M_order).astype(np.int),2)

E是输入十进制数据,M是二进制顺序。bindata是输出二进制数据,格式为1 x M二进制矩阵。

I found a method using matrix operation to convert decimal to binary.

import numpy as np
E_mat = np.tile(E,[1,M])
M_order = pow(2,(M-1-np.array(range(M)))).T
bindata = np.remainder(np.floor(E_mat /M_order).astype(np.int),2)

Eis input decimal data,M is the binary orders. bindata is output binary data, which is in a format of 1 by M binary matrix.


回答 28

这是一个不断循环的简单的二进制到十进制转换器

t = 1
while t > 0:
    binaryNumber = input("Enter a binary No.")
    convertedNumber = int(binaryNumber, 2)

    print(convertedNumber)

print("")

Here’s a simple binary to decimal converter that continuously loops

t = 1
while t > 0:
    binaryNumber = input("Enter a binary No.")
    convertedNumber = int(binaryNumber, 2)

    print(convertedNumber)

print("")

回答 29

这是我的回答,效果很好..!

def binary(value) :
    binary_value = ''
    while value !=1  :
        binary_value += str(value%2)
        value = value//2
    return '1'+binary_value[::-1]

This is my answer it works well..!

def binary(value) :
    binary_value = ''
    while value !=1  :
        binary_value += str(value%2)
        value = value//2
    return '1'+binary_value[::-1]

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