簡體   English   中英

在Python中檢查數字的奇偶校驗

[英]Checking parity of a number in Python

我試圖理解按位操作。 如果該位中的1的數目為奇數,則奇偶校驗為1,否則為0。

在下面的代碼中:

def parity(x):
    res = 0
    while x:
        res ^= x & 1
        x >>= 1
    return result

這給出了正確的結果,但是我不確定按位技巧如何工作。 我試圖用數字記下位的變化,但是仍然沒有直覺地解決這個問題。

我們為什么要用x & 1檢查XOR ,它們甚至意味着什么?

在此代碼中,“ res”的第一個初始化是將我們的res-state設置為偶數。 這是有道理的,因為我們尚未評估任何位,並且0是偶數。

然后,我們進入while循環,在其中循環移動x的位。

現在,我們通過對x的每個位與1進行“與”運算來評估它是否也為1( x&1 )。 然后,根據比較結果,我們將其與當前res狀態( res^=(x&1) )進行比較。

  • 如果res為偶數(0)且x位為1,則res求為奇數(1)。
  • 如果res為奇數(1)並且x位為1,則res求為偶數(0)。
  • 其他資源不變。

這樣,我們可以確保res根據x的奇偶性在偶數和奇數之間翻轉。

真值表也有助於思考問題:

res x  XOR out
 0  0  ->   0 // This is the state of even and no 1's found
 0  1  ->   1 // This is the state of even and then a 1 is found
 1  0  ->   1 // This is the state of odd and no 1's found
 1  1  ->   0 // This is the state of odd and then a 1 is found

希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM