lmarkov

Bit Check

Nov 27th, 2012
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. /*
  2.  * Write a boolean expression that returns if the bit at position p (counting from 0) in a given integer number v has value of 1. Example: v=5; p=1  false.
  3. */
  4.  
  5. using System;
  6.  
  7. class BitCheck
  8. {
  9.     static void Main()
  10.     {
  11.         int numberV, bitPositionP,numberMask, numberToCheck;
  12.         bool bitCheckResult;
  13.  
  14.         Console.WriteLine("Enter a number:");
  15.         if (int.TryParse(Console.ReadLine(), out numberV) && numberV >= int.MinValue && numberV <= int.MaxValue)
  16.         {
  17.             Console.WriteLine("Enter bit position which you want to check for 1 (count from 0): ");
  18.             if(int.TryParse(Console.ReadLine(), out bitPositionP) && bitPositionP >= int.MinValue && bitPositionP <= int.MaxValue)
  19.             {
  20.                 numberMask = 1 << bitPositionP;
  21.                 numberToCheck = numberV & numberMask;
  22.                 if (numberToCheck != 0)
  23.                 {
  24.                     bitCheckResult = true;
  25.                 }
  26.                 else
  27.                 {
  28.                     bitCheckResult = false;
  29.                 }
  30.                 Console.WriteLine("Bit position {0} for the number {1} is 1? -> {2}\n",bitPositionP, numberV, bitCheckResult);
  31.                 Main();
  32.             }
  33.         }
  34.         else
  35.         {
  36.             Console.WriteLine("Invalid input!\n");
  37.             Main();
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment