How do I properly loop through and print bits of an Int, Long, Float, or BigInteger?

血红的双手。 提交于 2019-12-24 08:15:47

问题


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.

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

回答1:


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;

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



回答2:


Convert.ToString(56,2).PadLeft(8,'0') returns "00111000"

This is for a byte, works for int also, just increase the numbers



来源:https://stackoverflow.com/questions/15315650/how-do-i-properly-loop-through-and-print-bits-of-an-int-long-float-or-biginte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!