使用for循环检查字节中的位

Elj*_*jay 0 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 ");

     if((val & t) == 0) 
         Console.Write("0 ");

   }
 }
}
Run Code Online (Sandbox Code Playgroud)

我无法理解为什么在for循环的递增/递减部分执行t = t/2.请解释一下

Jon*_*eet 5

十进制128是二进制10000000 - 即仅为字节的最高有效位的掩码.将它除以2时,得到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);
}
Run Code Online (Sandbox Code Playgroud)

  • 错字:1000000 = 64 (2认同)