Python int to binary string?

Czy istnieją jakieś metody Pythona do konwersji liczby całkowitej (lub długiej) na ciąg binarny w Pythonie?

W Google jest mnóstwo funkcji dec2bin ()... Ale miałem nadzieję, że przyda mi się wbudowana funkcja / biblioteka.

Author: dreftymac, 2009-03-31

30 answers

Metoda Pythona string format może przyjmować specyfikację formatu.

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

Format spec docs for Python 2

Format spec docs for Python 3

 861
Author: Tung Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 12:19:23

Jeśli szukasz bin() jako odpowiednik hex() został dodany w Pythonie 2.6.

Przykład:

>>> bin(10)
'0b1010'
 526
Author: John Fouhy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-13 23:33:47

Python rzeczywiście czy ma już coś wbudowanego do tego celu, możliwość wykonywania operacji takich jak '{0:b}'.format(42), która da ci wzorzec bitowy (w łańcuchu) dla 42 lub 101010.


Dla bardziej ogólnej filozofii, żaden język ani biblioteka nie da swojej bazie użytkowników wszystkiego , czego pragną. Jeśli pracujesz w środowisku, które nie zapewnia dokładnie tego, czego potrzebujesz, powinieneś zbierać urywki kodu podczas tworzenia, aby upewnić się, że nigdy nie musisz napisz to samo dwa razy. Np. pseudo-kod:

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

Który zbuduje Twój ciąg binarny na podstawie wartości dziesiętnej. Pamiętaj tylko, że jest to ogólny kawałek pseudo-kodu, który może nie być najbardziej efektywnym sposobem na zrobienie tego, jednak z iteracjami, które wydaje się proponować, nie zrobi to wielkiej różnicy. To tak naprawdę ma być tylko wskazówką, jak można to zrobić.

Ogólną ideą jest użycie kodu z (w kolejności "preference": {]}

  • język lub wbudowane biblioteki.
  • biblioteki innych firm z odpowiednimi licencjami.
  • Twoja własna kolekcja.
  • coś nowego musisz napisać (i zapisać we własnej kolekcji na później).
 65
Author: paxdiablo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-09 15:14:58

Jeśli chcesz reprezentację tekstową bez prefiksu 0b, możesz użyć tego:

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

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

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

Gdy chcesz reprezentację n-bitową:

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

Alternatywnie, jeśli wolisz mieć funkcję:

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)
 48
Author: Martin Thoma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-14 20:23:15

Jako odniesienie:

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

Ta funkcja może przekształcić dodatnią liczbę całkowitą tak dużą jak 18446744073709551615, reprezentowaną jako łańcuch '1111111111111111111111111111111111111111111111111111111111111111'.

Może być zmodyfikowany tak, aby obsługiwał znacznie większą liczbę całkowitą, choć może nie być tak przydatny jak "{0:b}".format() lub bin().

 39
Author: kctong529,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-17 19:39:08

Prostym sposobem na to jest użycie formatu string, zobacz tę stronę .

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

I jeśli chcesz mieć stałą długość ciągu binarnego, możesz użyć tego:

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

Jeśli wymagane jest dopełnianie dwójki, można użyć następującej linijki:

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

Gdzie n jest szerokością ciągu binarnego.

 23
Author: Xiang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-19 22:00:31

To jest dla Pythona 3 i zachowuje wiodące zera !

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

Tutaj wpisz opis obrazka

 21
Author: grepit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-13 07:04:23

Jednoliniowy zlambda :

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

Test:

>>> binary(5)
'101'



EDIT :

Ale potem: (

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

W porównaniu do

t1 = time()
for i in range(1000000):
    '{0:b}'.format(i)
t2 = time()
print(t2 - t1)
# 0.68017411232
 15
Author: Aziz Alto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-11 16:51:56

Podsumowanie alternatyw:

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.

Autorzy to John Fouhy, Tung Nguyen, mVChr, Martin Thoma . i Martijn Pieters.

 12
Author: BobStein-VisiBone,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:56

Jako odpowiedzi poprzedzające najczęściej używany format(), oto implementacja f-string.

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

Wyjście:

00111

Dla wygody tutaj jest link python docs dla sformatowanych literałów łańcuchowych: https://docs.python.org/3/reference/lexical_analysis.html#f-strings .

 12
Author: John Forbes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-07 20:41:01
>>> format(123, 'b')
'1111011'
 7
Author: Sandu Ursu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-07 15:17:31

Dla tych z nas, którzy muszą przekonwertować podpisane liczby całkowite(zakres -2**(cyfry-1) na 2**(cyfry-1)-1) na uzupełnione ciągi binarne 2, działa to:

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

To daje:

>>> int2bin(10, 8)
'00001010'
>>> int2bin(-10, 8)
'11110110'
>>> int2bin(-128, 8)
'10000000'
>>> int2bin(127, 8)
'01111111'
 7
Author: DeanM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-09-09 20:13:31

Jestem zaskoczony, że nie ma wzmianki o miłym sposobie osiągnięcia tego za pomocą ciągów formatujących. TLDR:

>>> number = 1
>>> f'0b{number:08b}'
'0b00000001'

Dłuższa historia

Jest to funkcjonalność formatowania ciągów:

>>> x, y, z = 1, 2, 3
>>> f'{x} {y} {2*z}'
'1 2 6'

Możesz również zażądać pliku binarnego:

>>> f'{z:b}'
'11'

Podaj szerokość:

>>> f'{z:8b}'
'      11'

Request zero padding:

f'{z:08b}'
'00000011'

I dodać wspólny prefiks oznaczający liczbę binarną:

>>> f'0b{z:08b}'
'0b00000011'

Możesz też pozwolić Pythonowi dodać prefiks dla ciebie, ale nie podoba mi się to tak bardzo, jak Wersja powyżej, ponieważ musisz wziąć przedrostek pod uwagę szerokość:

>>> f'{z:#010b}'
'0b00000011'

Więcej informacji można znaleźć w oficjalnej dokumentacji sformatowanych literałów łańcuchowych i Mini-języka specyfikacji formatu .

 6
Author: Roman Pavelka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-08 14:36:26

Używając numpy pack / unpackbits, są twoimi najlepszymi przyjaciółmi.

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)
 5
Author: pitfall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-27 03:39:36

Możesz TAK:

bin(10)[2:]

Lub:

f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c
 5
Author: Skiller Dz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-21 22:19:56

Chyba, że nie rozumiem, co masz na myśli przez ciąg binarny myślę, że moduł, którego szukasz to struct

 4
Author: Van Gale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-31 03:08:37

Jeszcze jedno rozwiązanie z innym algorytmem, za pomocą operatorów bitowych.

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

Szybsza wersja bez odwracania ciągu znaków.

def int2bin(val):
   res=''
   while val>0:
       res = chr((val&1) + 0x30) + res
       val=val>>1    
   return res 
 4
Author: Reza Abtin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-21 09:27:21
def binary(decimal) :
    otherBase = ""
    while decimal != 0 :
        otherBase  =  str(decimal % 2) + otherBase
        decimal    //=  2
    return otherBase

print binary(10)

Wyjście:

1010

 4
Author: mukundan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-25 01:00:08

W Pythonie 3.6 dodano nowe podejście do formatowania łańcuchów nazwane sformatowanymi literałami łańcuchów lub "F-strings". Przykład:

name = 'Bob'
number = 42
f"Hello, {name}, your number is {number:>08b}"

Wyjście będzie 'Witaj, Bob, Twój numer to 00001010!'

Dyskusja na ten temat znajduje się tutaj - Tutaj

 4
Author: Tim Uzlov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-27 13:47:52

Oto kod, który właśnie zaimplementowałem. Nie jest to metoda , ale można jej użyć jako gotowej do użycia funkcji!

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
 3
Author: quents,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-15 13:52:00
n=input()
print(bin(n).replace("0b", ""))
 3
Author: dblaze,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-29 13:35:47

numpy.binary_repr(num, width=None)

Przykłady z powyższego linku do dokumentacji:

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

Dopełniacz jest zwracany, gdy liczba wejściowa jest ujemna i podana jest szerokość:

>>> np.binary_repr(-3, width=3)
'101'
>>> np.binary_repr(-3, width=5)
'11101'
 3
Author: Tom Hale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-30 09:28:05

Nieco podobne rozwiązanie

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 
 2
Author: Chandler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-26 12:42:23

Oto proste rozwiązanie za pomocą funkcji divmod (), która zwraca przypomnienie i wynik dzielenia bez ułamka.

def dectobin(number):
    bin = ''
    while (number >= 1):
        number, rem = divmod(number, 2)
        bin = bin + str(rem)
    return bin
 2
Author: user210021,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-18 14:35:09

Oto jeszcze jeden sposób, używając zwykłej matematyki, bez pętli, tylko rekurencji. (Trywialny przypadek 0 nie zwraca nic).

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']
 2
Author: ergonaut,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-23 12:53:23

Kalkulator ze wszystkimi niezbędnymi funkcjami dla DEC, BIN, HEX: (made and tested with Python 3.5)

Możesz zmienić wejściowe numery testowe i uzyskać przekonwertowane.

# 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')
 2
Author: HKC72,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-29 08:11:23

aby obliczyć binarne liczby:

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

aby obliczyć liczbę dziesiętną Hexa:

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

Aby obliczyć wszystkie binarne no till 16::

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

Aby obliczyć liczbę dziesiętną Hexa no do 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
 2
Author: Rajesh Kumar Sahoo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-03 16:16:03

Zaakceptowana odpowiedź nie odnosi się do liczb ujemnych, które omówię. Oprócz powyższych odpowiedzi Możesz również użyć funkcji bin i hex . I w przeciwnym kierunku, użyj notacji binarnej:

>>> bin(37)
'0b100101'
>>> 0b100101
37

Ale przy ujemnych liczbach sprawy stają się nieco bardziej skomplikowane. Pytanie nie określa, w jaki sposób chcesz obsługiwać liczby ujemne.

Python dodaje znak ujemny, więc wynik dla -37 będzie taki:

>>> bin(-37)
'-0b100101'

W dane binarne komputera / sprzętu, znaki ujemne nie istnieją. Wszystko co mamy to 1 i 0. więc jeśli czytasz lub produkujesz binarne strumienie danych, które mają być przetwarzane przez inne oprogramowanie / Sprzęt, musisz najpierw znać notację, która jest używana.

Jedna notacja to notacja wielkości znaku , gdzie pierwszy bit reprezentuje znak ujemny, a reszta jest wartością rzeczywistą. W takim przypadku -37 byłoby 0b1100101, a 37 byłoby 0b0100101. To wygląda jak to, co tworzy python, ale wystarczy dodać 0 lub 1 Z Przodu dla liczb dodatnich / ujemnych.

Bardziej powszechną jest notacja dopełniacza Two , która wydaje się bardziej skomplikowana, a wynik jest bardzo różny od formatowania łańcuchów Pythona. Możesz przeczytać szczegóły w linku, ale z 8-bitową liczbą całkowitą -37 będzie 0b11011011, a 37 będzie 0b00100101.

Python nie ma łatwego sposobu na stworzenie tych binarnych reprezentacji. Możesz użyć numpy, aby zamienić wartości binarne dopełniacza Two w Pythona liczby całkowite:

>>> import numpy as np
>>> np.int8(0b11011011)
-37
>>> np.uint8(0b11011011)
219
>>> np.uint8(0b00100101)
37
>>> np.int8(0b00100101)
37

Ale nie znam łatwego sposobu na zrobienie czegoś odwrotnego z wbudowanymi funkcjami. Pakiet bitstring może jednak pomóc.

>>> from bitstring import BitArray
>>> arr = BitArray(int=-37, length=8)
>>> arr.uint
219
>>> arr.int
-37
>>> arr.bin
'11011011'
>>> BitArray(bin='11011011').int
-37
>>> BitArray(bin='11011011').uint
219
 2
Author: Dolf Andringa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-26 03:15:22
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")
 1
Author: Advay168,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-08 18:44:12

Znalazłem metodę wykorzystującą operację macierzy do konwersji dziesiętnej na binarną.

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)

Ejest wejściowymi danymi dziesiętnymi, {[2] } jest rozkazami binarnymi. bindata to wyjściowe dane binarne, które są w formacie 1 przez m macierzy binarnej.

 1
Author: Galle He,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-29 20:39:47