Python獲取數字的二進制值


目標

想要獲取一個整形數字的二進制表示

bin 內置函數

看一下官方的解釋

Convert an integer number to a binary string prefixed with “0b”. 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. Some examples。

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

If prefix “0b” is desired or not, you can use either of the following ways.

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}',f'{14:b}'
('0b1110', '1110')

可以看到bin函數返回二進制數字表示的形式是采用了負號,而不是補碼的形式。那么如何獲得補碼形式的二進制表示呢,很簡單只需要對數值進行與操作就可以。

>>> bin(-27 & 0b1111111111111111)
'0b1111111111100101'

這個例子手工指定了位數,也可以用下面帶參數的形式

def bindigits(n, bits):
    s = bin(n & int("1"*bits, 2))[2:]
    return ("{0:0>%s}" % (bits)).format(s)

>>> print bindigits(-31337, 24)
111111111000010110010111

歡迎關注我的微信公眾號

參考資料:
1、Python bin
2、Two's Complement Binary in Python?
3、integers


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM