2013-01-03 95 views

回答

56

使用按位運算符:

int getBit(int n, int k) { 
    return (n >> k) & 1; 
} 

說明(位):

n 
100010101011101010 (example) 
n >> 5 
000001000101010111 (all bits are moved over 5 spots, therefore 
&     the bit you want is at the end) 
000000000000000001 (0 means it will always be 0, 
=     1 means that it will keep the old value) 
1 
+1

這是從最顯著位開始作爲權利的第0位? – user1921187

+0

@ user1921187是的。 'getBit(0b10001,0)'會返回'1','getBit(0b10001,1)'會返回'0'。 – Doorknob

+0

好吧,如果我運行getBit(n,0),我會得到右邊第二位。所以k = 0實際上會讓我成爲最低有效位,所以它是第零位。我看到有什麼問題嗎? – user1921187

7
return (n >> k) & 1; 

這裏,n >> k轉移的k個位到最低顯著位置,並& 1屏蔽了一切。

4

如果最低顯著位位數0

return (n>>k)&1; 
0

您也可以使用該模塊財產爲此。如果你的數字是最低的有效位是零,否則(奇數)是一。

return (n>>k)%2; 
1

或使用:

boolean getBit(int n, int k) { 
    return (((n >> k) & 1) == 1 ? true:false); 
} 

如果你想有一個布爾值