How to scroll and print Int, Long, Float, or BigInteger bits correctly?

I am trying to debug some bit-changing operations, and I need to visualize the bits as they exist before and after the "Bit-shift" operation.

I read from this answer that I may have to handle reverse loading from switching, but I'm not sure what that means.

I think that by asking this question (how to print the bits in an int), I can find out what backfilling is, and maybe some other questions that I have.

Here is my sample code.

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 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
source share
2 answers

To check if the last bit is set, you can use:

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

But you must do this before going right (not after), otherwise you will not miss the first bit:

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

But the best 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 an array of bytes. The advantage (or disadvantage depending on your needs) of this method is that it reflects the reliability of the machine on which the code is running.

 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++; } 
+5
source
 Convert.ToString(56,2).PadLeft(8,'0') returns "00111000" 

This is for byte, works for int too, just increment numbers

+7
source

Source: https://habr.com/ru/post/1332411/


All Articles