[英]Is there a better way to convert from decimal to binary in python?
我需要將 integer 轉換為大小為 8 的列表,該列表是該數字(數字 <= 255)的二進制表示,然后返回。 目前我正在使用這些行
list(bin(my_num)[2:].rjust(8,'0'))
int("".join(my_list),2)
我做了一些谷歌搜索,但很難找到相關信息。 我只是好奇是否有更快或更標准的方法來做到這一點。
編輯:使用位掩碼會使它更快。 例如像這樣的東西
[(my_num>>y)&1 for y in xrange(7,-1,-1)]
就像我在評論中提到的那樣,我將它用於我正在編寫的隱寫術應用程序,所以我這樣做了數千次(圖像中每個像素 3 次),所以速度很好。
在Python 2.6或更高版本中,請使用format
語法 :
'{0:0=#10b}'.format(my_num)[2:]
# '00001010'
關於Python字符串的整潔事情之一是它們是序列。 如果您需要做的就是遍歷字符,則無需將字符串轉換為列表。
編輯 :對於隱寫術,您可能有興趣將字符流轉換為位流。 這是使用生成器的方法:
def str2bits(astr):
for char in astr:
n=ord(char)
for bit in '{0:0=#10b}'.format(n)[2:]:
yield int(bit)
並將位流轉換回字符流:
def grouper(n, iterable, fillvalue=None):
# Source: http://docs.python.org/library/itertools.html#recipes
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)
def bits2str(bits):
for b in grouper(8,bits):
yield chr(int(''.join(map(str,b)),2))
例如,您可以使用上述功能,例如:
for b in str2bits('Hi Zvarberg'):
print b,
# 0 1 0 0 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 0 0 0 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 0 1 0 1 1 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0 1 0 1 1 1 0 0 1 0 0 1 1 0 0 1 1 1
# To show bits2str is the inverse of str2bits:
print ''.join([c for c in bits2str(str2bits('Hi Zvarberg'))])
# Hi Zvarberg
此外,SO專家Ned Batchelder 在這里使用Python和PIL進行了一些與隱寫術相關的實驗。 您也許可以在那里找到一些有用的代碼。
如果發現需要更高的速度(並且仍然想用Python編寫此代碼),則可以考慮使用numpy 。
您可以使用zfill
代替rjust
。
list(bin(my_num)[2:].zfill(8))
這是將十進制轉換為二進制的一種方法:
可以將其編碼為:
d=int(raw_input("enter your decimal:"))
l=[]
while d>0:
x=d%2
l.append(x)
d=d/2
l.reverse()
for i in l:
print i,
print " is the decimal representation of givin binary data."
第一個解決方案:
快速方法不得使用循環。
我會建議使用您將構建一次並根據需要經常使用的查找表。
tb = []
for i in range(256):
tb.append( f"{i:08b}")
# once build you can use it for the whole image.
print( tb[27]) # will print: 00011011
第二種解決方案:
但是如果你真的很在意速度,你就不應該使用字符。 您應該將圖像加載到字節數組中(它是可變的)並直接修改像素中的位。
img[2][8] |≃ 0b10 # set second bit from right
img[2][8] |= 1<<1 # same
img[2][8] &= ~0b10 # reset second bit
img[2][8] &= ~1<<1 # same
img[2][8] ^= 0b1010 # invert second and fourth bits
我在這里給出了將十進制轉換為二進制的程序。
print "Program for Decimal to Binary Conversion"
n = 0
bin = 0
pos = 1
print "Enter Decimal Number:",
n = input()
while(n > 0):
bin = bin + (n % 2) * pos;
n = n / 2;
pos *= 10;
print "The Binary Number is: ", bin
#sample output
#Program for Decimal to Binary Conversion
#Enter Decimal Number: 10
#The Binary Number is: 1010
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.