Check if bit is set or not

How to check if a specific bit is set in a byte?

bool IsBitSet(Byte b,byte nPos) { return .....; } 
+46
c # bit-manipulation
Mar 12 '10 at 9:45
source share
8 answers

sounds like homework, but:

 bool IsBitSet(byte b, int pos) { return (b & (1 << pos)) != 0; } 

pos 0 is the least significant bit, position 7 is greater.

+110
Mar 12 '10 at 9:50
source share

Based on Mario Fernandez answered , I thought, why not use it in my tool as a convenient extension method, which is not limited to the data type, so I hope it is normal to share it here:

 /// <summary> /// Returns whether the bit at the specified position is set. /// </summary> /// <typeparam name="T">Any integer type.</typeparam> /// <param name="t">The value to check.</param> /// <param name="pos"> /// The position of the bit to check, 0 refers to the least significant bit. /// </param> /// <returns>true if the specified bit is on, otherwise false.</returns> public static bool IsBitSet<T>(this T t, int pos) where T : struct, IConvertible { var value = t.ToInt64(CultureInfo.CurrentCulture); return (value & (1 << pos)) != 0; } 
+10
May 14 '13 at 1:55
source share

Here is the solution in words.

On the left, shift an integer with an initial value of 1 n times, and then execute AND with the original byte. If the result is nonzero, the bit is set differently. :)

+5
Mar 12
source share

This also works (tested in .NET 4):

 void Main() { //0x05 = 101b Console.WriteLine(IsBitSet(0x05, 0)); //True Console.WriteLine(IsBitSet(0x05, 1)); //False Console.WriteLine(IsBitSet(0x05, 2)); //True } bool IsBitSet(byte b, byte nPos){ return new BitArray(new[]{b})[nPos]; } 
+5
May 14 '11 at 2:35 a.m.
source share

Slide your input n bits down and fill 1, then check if you have 0 or 1.

+3
Mar 12 '10 at 9:50
source share
 x == (x | Math.Pow(2, y)); int x = 5; x == (x | Math.Pow(2, 0) //Bit 0 is ON; x == (x | Math.Pow(2, 1) //Bit 1 is OFF; x == (x | Math.Pow(2, 2) //Bit 2 is ON; 
+2
Jul 28 '12 at 19:57
source share

something like

 return ((0x1 << nPos) & b) != 0 
0
Mar 12 '10 at 9:50
source share

To check bits in a 16-bit word:

  Int16 WordVal = 16; for (int i = 0; i < 15; i++) { bitVal = (short) ((WordVal >> i) & 0x1); sL = String.Format("Bit #{0:d} = {1:d}", i, bitVal); Console.WriteLine(sL); } 
0
May 9 '12 at 19:57
source share



All Articles