如何正确遍历并打印Int,Long,Float或BigInteger的位? [英] How do I properly loop through and print bits of an Int, Long, Float, or BigInteger?

查看:257
本文介绍了如何正确遍历并打印Int,Long,Float或BigInteger的位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to debug some bit shifting operations and I need to visualize the bits as they exist before and after a Bit-Shifting operation.

我从这个答案中了解到,我可能需要处理移位带来的回填,但是我不确定就是这个意思.

I read from this answer that I may need to handle backfill from the shifting, but I'm not sure what that means.

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

I think that by asking this question (how do I print the bits in a int) I can figure out what the backfill is, and perhaps some other questions I have.

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

Here is my sample code so far.

    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");
        }
    }

推荐答案

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

To test if the last bit is set you could use:

isBitSet = ((bits & 1) == 1);

但是您应该在向右移动之前(而不是向后移动)这样做,否则,您将缺少第一位:

But you should do so before shifting right (not after), otherwise you's missing the first bit:

isBitSet = ((bits & 1) == 1);
bits = bits >> 1;

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

But a better option would be to use the static methods of the BitConverter class to get the actual bytes used to represent the number in memory into a byte array. The advantage (or disadvantage depending on your needs) of this method is that this reflects the endianness of the machine running the code.

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++;
}

这篇关于如何正确遍历并打印Int,Long,Float或BigInteger的位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆