需要一个方法来返回int的特定位的值

5Yr*_*DBA 2 java

我想我需要一个像这样的实用方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

我正在研究如何做到这一点.如果你们中的任何人手头有代码,请与我分享.谢谢

Jon*_*eet 5

做一个班次和面具:

return (short) ((intNum >> pos) & 1);
Run Code Online (Sandbox Code Playgroud)

当然,假设你想要一个返回值1或0.如果您想要位本身,仍然具有相同的值,则需要将返回类型更改为int并使用:

return intNum & (1 << intNum);
Run Code Online (Sandbox Code Playgroud)