如何正确循环并打印Int,Long,Float或BigInteger的位?

goo*_*ate 1 c# pointers bits bit-shift

我正在尝试调试一些位移操作,我需要在Bit-Shifting操作之前和之后可视化位.

我从这个答案读到,我可能需要处理来自变换的回填,但我不确定这意味着什么.

我想通过提出这个问题(我如何打印int中的位)我可以弄清楚回填是什么,也许我还有其他一些问题.

这是我到目前为止的示例代码.

    static string GetBits(int num)
    {
        StringBuilder sb = new StringBuilder();
        uint bits = (uint)num;
        while (bits!=0)
        {
            bits >>= 1;

            isBitSet =  // somehow do an | operation on the first bit.
                        // I'm unsure if it's possible to handle different data types here
                        // or if unsafe code and a PTR is needed

            if (isBitSet)
                sb.Append("1");
            else
                sb.Append("0");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Flo*_*res 8

Convert.ToString(56,2).PadLeft(8,'0') returns "00111000"
Run Code Online (Sandbox Code Playgroud)

这是一个字节,也适用于int,只是增加数字


Mik*_*scu 6

要测试是否设置了最后一位,您可以使用:

isBitSet = ((bits & 1) == 1);
Run Code Online (Sandbox Code Playgroud)

但是你应该在向右移动之前(而不是之后)这样做,否则你会错过第一位:

isBitSet = ((bits & 1) == 1);
bits = bits >> 1;
Run Code Online (Sandbox Code Playgroud)

但更好的选择是使用BitConverter类的静态方法来获取用于将内存中的数字表示为字节数组的实际字节.此方法的优点(或缺点取决于您的需要)是这反映了运行代码的机器的字节顺序.

byte[] bytes = BitConverter.GetBytes(num);

int bitPos = 0;
while(bitPos < 8 * bytes.Length)
{
   int byteIndex = bitPos / 8;
   int offset = bitPos % 8;
   bool isSet = (bytes[byteIndex] & (1 << offset)) != 0;

   // isSet = [True] if the bit at bitPos is set, false otherwise

   bitPos++;
}
Run Code Online (Sandbox Code Playgroud)