Is there a better way to convert from decimal to binary in python?

I need to convert from an integer to a list of size 8, which is a binary representation of that number (number <= 255) and vice versa. I am currently using these lines

list(bin(my_num)[2:].rjust(8,'0'))
int("".join(my_list),2)

I did some searches, but it was difficult for me to find the relevant information. I'm just wondering if there is a faster or more standard way to do this.

change Using bitmask will make it faster. For instance. something like that

[(my_num>>y)&1 for y in xrange(7,-1,-1)]

As I mentioned in the commentary, I use this for the steganography application that I write, so I do it thousands of times (3 times per pixel in the image), so the speed is good.

+3
source share
4 answers

In Python 2.6 or later, use format syntax :

'{0:0=#10b}'.format(my_num)[2:]
# '00001010'

One neat thing about Python strings is that they are sequences. If all you have to do is iterate over the characters, then there is no need to convert the string to a list.

Change . For steganography, you might be interested in converting a character stream to a bit stream. Here's how you could do it with generators:

def str2bits(astr):
    for char in astr:    
        n=ord(char)
        for bit in '{0:0=#10b}'.format(n)[2:]:
            yield int(bit)

And to convert the bitstream back to a character stream:

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 example, you could use the above functions as follows:

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.

+4

zfill rjust.

list(bin(my_num)[2:].zfill(8))
+3

:

  • 2
  • 2
  • ,
  • ,

:

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."
+1

.

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

Source: https://habr.com/ru/post/1731221/


All Articles