Python int to binary string?

后端 未结 30 1634
执念已碎
执念已碎 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:46

    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 Fouhy, Tung Nguyen, mVChr, Martin Thoma. and Martijn Pieters.

提交回复
热议问题