Python int to binary string?

后端 未结 30 1673
执念已碎
执念已碎 2020-11-22 05:34

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google... But I

30条回答
  •  逝去的感伤
    2020-11-22 05:57

    If you are willing to give up "pure" Python but gain a lot of firepower, there is Sage - example here:

    sage: a = 15
    sage: a.binary()
    '1111'
    

    You'll note that it returns as a string, so to use it as a number you'd want to do something like

    sage: eval('0b'+b)
    15
    

提交回复
热议问题