Changes the value in the given position. Change bit value from low to high, or high to low. Returns the same byte, but with one bit changed. - CSharp System

CSharp examples for System:Byte

Description

Changes the value in the given position. Change bit value from low to high, or high to low. Returns the same byte, but with one bit changed.

Demo Code


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

public class Main{
        public static UInt32 FlipBit(UInt32 data, ushort bitposition)
        {
            UInt32 mask = (UInt32)(1 << bitposition);
            if (CheckBit(data, bitposition))
                return (UInt32)(data & ~mask);
            else
                return (UInt32)(data | mask);
        }
        /// <summary>
        /// Changes the value in the given position. Change bit value from low to high, or high to low.
        /// Returns the same byte, but with one bit changed.
        /// </summary>
        public static byte FlipBit(byte data, ushort bitposition)
        {
            byte mask = (byte)(1 << bitposition);
            if (CheckBit(data, bitposition))
                return (byte)(data & ~mask);
            else
                return (byte)(data | mask);
        }
        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