[Solved] Bitwise in C#: Check a Bit at Given Position

  

5
Topic starter

Write a Boolean expression that returns if the bit at position p (counting from 0, starting from the right) in given integer number n has value of 1.

Examples:

check bit at given position in C#

1 Answer
4

Here is my solution to it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
 
class CheckABitAtGivenPosition
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        int p = int.Parse(Console.ReadLine());
 
        int nRightp = n >> p;
        int bit = nRightp & 1;
 
        bool check = (bit == 1);//by default boolean expressions are set to true
        Console.WriteLine(check);
    }
}
Share: