Bitwise checks it the given bit is set in the data. - CSharp System

CSharp examples for System:Bit

Description

Bitwise checks it the given bit is set in the data.

Demo Code


using System.Text;
using System.Collections.Generic;
using System;/*from w  ww.j a  v  a 2 s  . c  o m*/

public class Main{
        public static bool CheckBit(byte data, byte bit)
        {
            byte mask = (byte)(1 << bit);
            return (data & mask) != 0;
        }
        public static bool CheckBit(UInt32 data, ushort bit)
        {
            UInt32 mask = (UInt32)(1 << (int)bit);
            return (data & mask) != 0;
        }
        /// <summary>
        /// Bitwise checks it the given bit is set in the data.
        /// </summary>
        /// <param name="bit">The zero-based position of a bit. I.e. bit 1 is the second bit.</param>
        /// <returns>Returns TRUE if bit is set.</returns>
        public static bool CheckBit(UInt16 data, ushort bit)
        {
            //A single bit is LEFT SHIFTED the number a given number of bits.
            //and bitwise AND'ed together with the data.
            //So the initial value is   :       0000 0000.
            //Left shifting a bit 3 bits:       0000 0100
            //And'ed together with the data:    0101 0101 AND 0000 01000 => 0000 0100 (which is greater than zero - so bit is set).

            ushort mask = (ushort)(1 << (ushort)bit);
            return (data & mask) != 0;
        }
}

Related Tutorials