[英]How do I properly loop through and print bits of an Int, Long, Float, or 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. 我从这个答案中得知,我可能需要处理移位后的回填,但是我不确定这意味着什么。
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. 我认为,通过问这个问题(如何在int中打印位),我可以弄清楚回填是什么,也许还有其他一些问题。
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");
}
}
Convert.ToString(56,2).PadLeft(8,'0') returns "00111000"
这是一个字节,也可以用于int,只是增加数字
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. 但是更好的选择是使用BitConverter类的静态方法将用于表示内存中数字的实际字节转换为字节数组。 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++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.