簡體   English   中英

Python int 到二進制字符串?

[英]Python int to binary string?

是否有任何罐裝 Python 方法可以將 Integer(或 Long)轉換為 Python 中的二進制字符串?

谷歌上有無數的 dec2bin() 函數......但我希望我可以使用內置函數/庫。

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

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

格式化 Python 2 的規范文檔

格式化 Python 3 的規范文檔

如果您正在尋找與hex()等效的bin() hex() ,它是在 python 2.6 中添加的。

例子:

>>> bin(10)
'0b1010'

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

這將根據十進制值構造您的二進制字符串。 請記住,這是一段通用的偽代碼,雖然它可能不是有效的方法,但對於您似乎提出的迭代,它不會產生太大影響。 它實際上只是作為如何完成的指南。

總體思路是使用以下代碼(按優先順序):

  • 語言或內置庫。
  • 具有合適許可證的第三方庫。
  • 你自己的收藏。
  • 你需要寫一些新的東西(並保存在你自己的收藏中以備后用)。

如果你想要一個沒有 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)

作為參考:

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

該函數可以轉換一個大到18446744073709551615的正整數,表示為字符串'1111111111111111111111111111111111111111111111111111111111111111'

可以修改它以提供更大的整數,盡管它可能不如"{0:b}".format()bin()

這是針對python 3的,它保留了前導零!

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

在此處輸入圖片說明

一種簡單的方法是使用字符串格式,請參閱此頁面

>> "{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 是二進制字符串的寬度。

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

我很驚訝沒有提到使用 Python 3.6 及更高版本支持的格式化字符串來完成此操作的好方法。 域名注冊地址:

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

更長的故事

這是 Python 3.6 提供的格式化字符串的功能:

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

您也可以請求二進制文件:

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

指定寬度:

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

請求零填充:

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

並添加公共前綴來表示二進制數:

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

您也可以讓 Python 為您添加前綴,但我不像上面的版本那么喜歡它,因為您必須考慮前綴的寬度:

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

更多信息可在Formatted string literalsFormat Specification Mini-Language 的官方文檔中找到。

由於前面的答案主要使用 format(),這里是一個 f-string 實現。

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

輸出:

00111

為方便起見,這里是格式化字符串文字的 python 文檔鏈接: https : //docs.python.org/3/reference/lexical_analysis.html#f-strings

備選方案摘要:

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 和馬丁·彼得斯。

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

對於我們這些需要將有符號整數(范圍 -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'

使用 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)

你可以這樣做:

bin(10)[2:]

或者 :

f = str(bin(10))
c = []
c.append("".join(map(int, f[2:])))
print c
def binary(decimal) :
    otherBase = ""
    while decimal != 0 :
        otherBase  =  str(decimal % 2) + otherBase
        decimal    //=  2
    return otherBase

print binary(10)

輸出:

1010

通過使用按位運算符,另一種算法的另一種解決方案。

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 

接受的答案沒有解決負數,我將介紹。 除了上面的答案,您還可以只使用binhex函數。 在相反的方向,使用二進制表示法:

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

但是對於負數,事情變得有點復雜。 這個問題沒有指定你想如何處理負數。

Python 只是添加了一個負號,所以 -37 的結果是這樣的:

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

在計算機/硬件二進制數據中,不存在負號。 我們只有1和0。 因此,如果您正在讀取或生成要由其他軟件/硬件處理的二進制數據流,您首先需要知道所使用的符號。

一種表示法是符號幅度表示法,其中第一位表示負號,其余表示實際值。 在這種情況下, -37 將是0b1100101 , 37 將是0b0100101 這看起來像 python 產生的,但只需在正/負數前面添加 0 或 1。

更常見的是Two'scomplement notation ,它看起來更復雜,結果與python的字符串格式有很大不同。 您可以閱讀鏈接中的詳細信息,但使用 8 位有符號整數 -37 將是0b11011011而 37 將是0b00100101

Python 沒有簡單的方法來生成這些二進制表示。 您可以使用numpy將二進制補碼二進制值轉換為 python 整數:

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

但是我不知道用內置函數做相反的事情的簡單方法。 不過,位串包可以提供幫助。

>>> 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

Python 3.6 添加了一種新的字符串格式化方法,稱為格式化字符串文字或“f-strings”。 例子:

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

輸出將是“你好,鮑勃,你的號碼是 00001010!”

關於這個問題的討論可以在這里找到 - 這里

除非我誤解了二進制字符串的意思,否則我認為您要查找的模塊是struct

這是我剛剛實現的代碼。 這不是一種方法,但您可以將其用作現成的功能

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
n=input()
print(bin(n).replace("0b", ""))

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'

有點類似的解決方案

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 

這是使用 divmod() 函數的簡單解決方案,它返回提醒和不帶分數的除法結果。

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

這是使用常規數學的另一種方法,沒有循環,只有遞歸。 (普通情況 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']

帶有 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')

計算二進制數:

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

如果你願意放棄“純粹的”Python而獲得大量的火力, 那么就有Sage - 這里的例子如下:

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

您會注意到它以字符串形式返回,因此要將其用作您想要執行某些操作的數字

sage: eval('0b'+b)
15
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")

我找到了一種使用矩陣運算將十進制轉換為二進制的方法。

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×M二進制矩陣。

沿着與Yusuf Yazici的答案類似的路線

def intToBin(n):
    if(n < 0):
        print "Sorry, invalid input."
    elif(n == 0):
        print n
    else:
        result = ""
        while(n != 0):
            result += str(n%2)
            n /= 2
        print result[::-1]

我對它進行了調整,以便變異的唯一變量是結果(當然是n)。

如果您需要在其他地方使用此功能(即,將結果用於其他模塊),請考慮以下調整:

def intToBin(n):
    if(n < 0):
        return -1
    elif(n == 0):
        return str(n)
    else:
        result = ""
        while(n != 0):
            result += str(n%2)
            n /= 2
        return result[::-1]

因此-1將是您的哨兵值,表明轉換失敗。 (假設您只轉換正數,無論它們是整數還是長數)。

這是一個簡單的二進制到十進制轉換器,它不斷循環

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

    print(convertedNumber)

print("")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM