C# 使用for循环检查字节中的位
我最近正在学习C语言,在那里我遇到了以下for循环C# 使用for循环检查字节中的位,c#,C#,我最近正在学习C语言,在那里我遇到了以下for循环 // Display the bits within a byte. using System; class ShowBits { static void Main() { int t; byte val; val = 123; for(t=128; t > 0; t = t/2) { if((val & t) != 0) Console.Write("1 ");
// Display the bits within a byte.
using System;
class ShowBits {
static void Main() {
int t;
byte val;
val = 123;
for(t=128; t > 0; t = t/2) {
if((val & t) != 0)
Console.Write("1 ");
if((val & t) == 0)
Console.Write("0 ");
}
}
}
我无法理解为什么在for循环的递增/递减部分执行t=t/2。plz explaint用作val中位的掩码。 所以它从12810000000二进制开始。 当它除以2时,它变成64-或01000000。 直到它达到0为止
然后在每次迭代中,使用“&”将val中的位与t中的当前位屏蔽。它以2的幂递减循环,并在屏蔽中使用该值 基数10:128,64,32,16,8,4,2,1
基数2:10000000、01000000、00100000、00010000、000011000、00000、100000000、10000000000、1000000000001十进制128是二进制10000000-即仅用于字节最高位的掩码。当你把它除以二,你得到01000000,也就是第二个最高有效位,以此类推 在原始值和掩码之间使用&并仅与0进行比较,表示该位是否设置在原始值中 另一种替代方法是移动原始值:
for (int i = 7; i >= 0; i--)
{
int shifted = val >> i;
// Take the bottom-most bit of the shifted value
Console.Write("{0} ", shifted & 1);
}
128以二进制形式写入10000000,因此我们检查字节中的最高位是否为on。然后我们做t=t/2,也就是t=128/2=64,在二进制中写为01000000,以此类推。任何除法都会将一个位置上的一位向右移动。@MitchWheat:干杯-我可以发誓我会加上7个零: