1
print 077777#how can i get binary

i use python2.5

1
  • 1
    are you asking how you can print an integer in binary? Commented Jan 3, 2010 at 3:27

4 Answers 4

6

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'
Sign up to request clarification or add additional context in comments.

2 Comments

I'd probably make this return 0b prepended, for compatibility with the built-in bin function present in Python 2.6.
return '-0b'[value>=0:] + ... % (abs(value),) ... to make it support negative numbers and be compatible with bin
1

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

def dobin(n):
  digs = []
  s = ''
  if n<0:
    s = '-'
    n = -n
  while True:
    digs.append(str(n % 2))
    n /= 2
    if not n: break
  if s: digs.append(s)
  digs.reverse()
  return ''.join(digs)

Are you looking for speed, or for clarity?

Comments

1

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)

Comments

1
n = 1234

"".join([["0", "1"][(n >> i) & 1] for i in reversed(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 in range(log(n,2)+1)])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.