获取十进制数转换为二进制后某一位的值

这段代码展示了如何使用位移和位与操作来判断整数中特定位置的二进制位是否为1。内部函数DeterminesValueOfOneBitInBinary和ReadInt32Bit分别用于获取指定位置的二进制位值和判断给定位置的位是否为1。这些方法在计算机科学和编程中常用于高效地处理二进制数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码参考如下:

		// 具体做法是将十进制数通过[>>]操作符右移,然后再和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;
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值