Latest web development tutorials

Python 練習實例55

Python 100例 Python 100例

題目:學習使用按位取反~。

程序分析: ~0=1; ~1=0;
(1)先使a右移4位。
(2)設置一個低4位全為1,其餘全為0的數。 可用~(~0<<4)
(3)將上面二者進行&運算。

程序源代碼:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

if __name__ == '__main__':
    a = 234
    b = ~a
    print 'The a\'s 1 complement is %d' % b
    a = ~a
    print 'The a\'s 2 complement is %d' % a

以上實例輸出結果為:

The a's 1 complement is -235
The a's 2 complement is -235

Python 100例 Python 100例