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;
source share