代码参考如下:
// 具体做法是将十进制数通过[>>]操作符右移,然后再和1求【与】。和1求与相当于和[00000001]求与,这样得到的结果只需要看最后一位是否为1就好。 注:[&]操作符简介: 1&1=1; 0&1=0; 0&0=0; 1&0=0 (简单说就是只有[1&1]为1,其它结果都是0)
internal bool DeterminesValueOfOneBitInBinary( int nNeedConvertedToBinary, int nDigitsID, out byte bytValue )
{
// ID为从1开始
if( nDigitsID <= 0 ) {
bytValue =0;
return false;
}
bytValue = (byte)( ( nNeedConvertedToBinary >> ( nDigitsID - 1 ) ) & 1 );
return true;
}
// Determines the value of a bit in binary
internal bool ReadInt32Bit( int nInputValue, int nBitPosition, ref bool isBitOn )
{
// 1 Byte = 8 bits
int nMaxBitSize = 8 * sizeof( int );
// nBitPosition is 0 Base
if( nBitPosition < 0 || nBitPosition >= nMaxBitSize ) {
isBitOn = false;
return false;
}
if( (byte)( ( nInputValue >> nBitPosition ) & 1 ) == 0 ) {
isBitOn = false;
}
else {
isBitOn = true;
}
return true;
}