Skip to content Skip to sidebar Skip to footer

How Change Int To Binary. On Python 2.5

print 077777#how can i get binary i use python2.5

Solution 1:

Make a map of hexadecimal characters to binary sequences, then run the number through (note: only works for non-negative numbers):

def bin(value):
    binmap = {'0': '0000', '1': '0001', ..., 'f': '1111'}
    return''.join(binmap[x] for x in('%x' % (value,))).lstrip('0') or '0'

Solution 2:

Simplest (not fastest!) way to get a binary string for an int in Python 2.5:

defdobin(n):
  digs = []
  s = ''if n<0:
    s = '-'
    n = -n
  whileTrue:
    digs.append(str(n % 2))
    n /= 2ifnot n: breakif s: digs.append(s)
  digs.reverse()
  return''.join(digs)

Are you looking for speed, or for clarity?

Solution 3:

Here are some recipes from ActiveState Code you might find helpful: Format integer as binary string


My initial answer only works in Python 2.6 and up as Alex correctly pointed out.

Like this:

print '{0:b}'.format(077777)

Solution 4:

n = 1234"".join([["0", "1"][(n >> i) & 1] for i inreversed(range(n.__sizeof__()))])

although not sure if sizeof its correct.you could also calculate the highest bit set and only print those.

"".join([["0", "1"][(n>>i)&1] for i inrange(log(n,2)+1)])

Post a Comment for "How Change Int To Binary. On Python 2.5"