Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Write an expression that extracts from a given integer i the value of a given bit number b. Example: i=5; b=2 value=1.
- */
- using System;
- class ExtractBitFromNumber
- {
- static void Main()
- {
- int numberI, bitNumberB, numberMask, numberToCheck, bitCheckResult;
- string error1 = "Invalid input! Please enter a number between " + int.MinValue + " and " + int.MaxValue + ".\n";
- Console.WriteLine("Enter a number:");
- if (int.TryParse(Console.ReadLine(), out numberI) && numberI >= int.MinValue && numberI <= int.MaxValue)
- {
- Console.WriteLine("Enter bit position which you want to check (count from 0): ");
- if (int.TryParse(Console.ReadLine(), out bitNumberB) && bitNumberB >= int.MinValue && bitNumberB <= int.MaxValue)
- {
- numberMask = 1 << bitNumberB;
- numberToCheck = numberI & numberMask;
- if (numberToCheck == 0)
- {
- bitCheckResult = 0;
- }
- else
- {
- bitCheckResult = 1;
- }
- Console.WriteLine("Value of bit number {0} for number {1} is: {2}\n", bitNumberB, numberI, bitCheckResult);
- Main();
- }
- else
- {
- Console.WriteLine(error1);
- Main();
- }
- }
- else
- {
- Console.WriteLine(error1);
- Main();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment