2011-05-17 35 views
2

我想我需要一個實用的方法是這樣的特定位的值:需要一個方法返回一個int

public static short bitValue(int intNum, short pos) 
{ 
    short bitValue = 0; 

    //check pos bit (from right to left) in the intNum integer to see its value is 0 or 1 
    //And then update the bitValue for return 

    return bitValue; 
} 

我做的研究,以瞭解如何現在就這樣做。如果你們中的任何人有手碼,請與我分享。感謝

回答

5

只是做一個轉變和掩碼:

return (short) ((intNum >> pos) & 1); 

這是假設你想當然的1或0返回值。如果你想一點本身,還是使用相同的值,你需要將自己的返回類型更改爲int及用途:

return intNum & (1 << intNum); 
+0

我只想知道由pos參數指定的那個位的值。謝謝。我現在需要回顧一下這些轉換操作符。 – 5YrsLaterDBA 2011-05-17 18:54:53

0

如果你有一個多字的價值位的處理,可以考慮使用位集合。

相關問題