Python Convert int to binary

bin ( x )

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

New in version 2.6.


up vote 186 down vote accepted

Python's string format method can take a format spec. 

>>> "{0:b}".format(10)
'1010'

Format spec docs for Python 2

Format spec docs for Python 3

share improve this answer
 
12 
str.format() is new in version 2.6: docs.python.org/library/stdtypes.html –  Mark Roddy  Mar 31 '09 at 3:19
2 
Thank you Tung. What is a pythonic way to reverse this operation? –  kalu  Oct 23 '14 at 16:40
4 
to convert a binary string to an integer, just use int(): int(x,2) –  RufusVS  Apr 18 '15 at 3:42
1 
for padding, add .zfill(n) where n is the number of bits. –  mike  Jul 14 '15 at 23:50
7 
str.format() just to format one value is overkill. Go straight to the format() functionformat(n, 'b'). There is no need to parse out the placeholder and match it to an argument, go straight for the value formatting operation itself. Only use str.format() if you need to place the formatted result in a longer string (e.g. use it as a template). –  Martijn Pieters  Dec 10 '15 at 10:23 

If you're looking for bin() as an equivalent to hex(), it was added in python 2.6.

Example:

>>> bin(10)
'0b1010'
share improve this answer
 
26 
Note also that it's faster to do str(bin(i))[2:] (0.369s for 1000000ops) than "{0:b}".format(i)(0.721s for 1000000ops) –  mVChr  Oct 30 '13 at 7:55
11 
@mVChr if someone's converting numbers into an ASCII binary representation, I really hope speed doesn't matter. –  Nick T  Feb 5 '14 at 5:04
8 
@mVChr bin() returns a string without str() –  Air  Feb 21 '14 at 17:34 
3 
@mVChr: str.format() is the wrong tool anyway, you would use format(i, 'b') instead. Take into account that that also gives you padding and alignment options though; format(i, '016b') to format to a 16-bit zero-padded binary number. To do the same with bin() you'd have to add a str.zfill() call: bin(i)[2:].zfill(16) (no need to call str()!). format()'s readability and flexibility (dynamic formatting is much harder with bin()) are great tradeoffs, don't optimise for performance unless you have to, until then optimise for maintainability. –  Martijn Pieters  Dec 10 '15 at 10:28 

No language or library will give its user base everything that they desire. If you're working in an envronment that doesn't provide exactly what you need, you should be collecting snippets of code as you develop to ensure you never have to write the same thing twice. Such as, for example:

def int2bin(i):
    if i == 0: return "0"
    s = ''
    while i:
        if i & 1 == 1:
            s = "1" + s
        else:
            s = "0" + s
        i /= 2
    return s

which will construct your binary string based on the decimal value.

Fortunately, however, Python has something already built in, the ability to do operations such as '{0:b}'.format(42), which will give you the bit pattern for 42, or 101010.

The general idea is to use code from (in order of preference):

  • the language or built-in libraries.
  • third-party libraries with suitable licenses.
  • your own collection.
  • something new you need to write (and save in your own collection for later).
share improve this answer
 
6 
I like your general coding comments. –  Cosine  Dec 27 '13 at 1:14
1 
I too like your comments, which is why I did not downvote you for disregarding your own advice. –  Mad Physicist  Oct 21 '15 at 17:37

As a reference:

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

This function can convert a positive integer as large as 18446744073709551615, represented as string '1111111111111111111111111111111111111111111111111111111111111111'.

It can be modified to serve a much larger integer, though it may not be as handy as "{0:b}".format() or bin().

share improve this answer
 
 
Having an old version of Python this is exactly what I needed, thank you. –  Gaz Davidson  Mar 19 '14 at 14:43
 
Clever. Crafty. –  Mad Physicist  Oct 21 '15 at 17:38

If you want a textual representation without the 0b-prefix, you could use this:

get_bin = lambda x: format(x, 'b')

print(get_bin(3))
>>> '11'

print(get_bin(-3))
>>> '-11'

When you want a n-bit representation:

get_bin = lambda x, n: format(x, 'b').zfill(n)
>>> get_bin(12, 32)
'00000000000000000000000000001100'
>>> get_bin(-12, 32)
'-00000000000000000000000000001100'
share improve this answer
 
2 
Or just use format(integer, 'b')bin() is a debugging tool, specifically aimed at producing the Python binary integer literal syntaxformat() is meant to produce specific formats. –  Martijn Pieters  Dec 10 '15 at 10:21 
 
@MartijnPieters Thank you very much for mentioning it. I've adjusted my solutution. How do you know that bin() is a debugging tool aimed at producing the Python binary integer literal syntax? I couldn't find that in the documentation. –  Martin Thoma  Dec 10 '15 at 10:36
1 
From the documentation: The result is a valid Python expression. It's aim is to produce a Python expression, not to produce end-user representations. The same applies to oct() and hex(). –  Martijn Pieters  Dec 10 '15 at 10:37
1 
More alternatives: If you are going to make the width dynamic, instead of str.zfill() you could use str.format() or format() with a dynamic second argument: '{0:0{1}b}'.format(x, n) or format(b, '0{}b'.format(n)). –  Martijn Pieters  Dec 10 '15 at 10:41
 
@MartijnPieters Wow, thank you very much for this input! I didn't know that this was possible with format. However, I think my current answer with zfill is easier to read and understand than the dynamic second argument, so I'll keep that. –  Martin Thoma  Dec 10 '15 at 10:45

one-liner with lambda:

>>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)

test:

>>> binary(5)
'101'



EDIT

but then :( 

t1 = time()
for i in range(1000000):
     binary(i)
t2 = time()
print(t2 - t1)
# 6.57236599922

in compare to 

t1 = time()
for i in range(1000000):
    '{0:b}'.format(i)
t2 = time()
print(t2 - t1)
# 0.68017411232
share improve this answer
 
 
I like the recursive lambda. –  Mad Physicist  Oct 21 '15 at 17:41

Unless I'm misunderstanding what you mean by binary string I think the module you are looking for is struct

share improve this answer
 
def binary(decimal) :
    otherBase = ""
    while decimal != 0 :
        otherBase  =  str(decimal % 2) + otherBase
        decimal    /=  2
    return otherBase

print binary(10)

output:

1010

share improve this answer
 

Summary of alternatives:

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.

Contributors include John FouhyTung NguyenmVChrmoose. and Martijn Pieters.

share improve this answer
 
1 
str.format() just to format one value is overkill. Go straight to the format() function: format(n, 'b'). No need to parse out the placeholder and match it to an argument that way. –  Martijn Pieters  Dec 10 '15 at 10:23 

Yet another solution with another algorithm, by using bitwise operators. 

def int2bin(val):
    res=''
    while val>0:
        res += str(val&1)
        val=val>>1     # val=val/2 
    return res[::-1]   # reverse the string

A faster version without reversing the string.

def int2bin(val):
   res=''
   while val>0:
       res = chr((val&1) + 0x30) + res
       val=val>>1    
   return res 
share improve this answer
 

Here is the code I've just implemented. This is not a method but you can use it as a ready-to-use function!

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
share improve this answer
 

here is simple solution using the divmod() fucntion which returns the reminder and the result of a division without the fraction.

def dectobin(number):
    bin = ''
    while (number >= 1):
        number, rem = divmod(number, 2)
        bin = bin + str(rem)
    return bin
share improve this answer
bin ( x )

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

New in version 2.6.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值