Advertisement
Klaxon

[C# Operators] Extracts Bit Number

Jul 9th, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.14 KB | None | 0 0
  1. // Write an expression that extracts from a given integer i the value of a given bit number b.
  2. // Example: i=5; b=2 --> value=1.
  3.  
  4. using System;
  5.  
  6. class ExtractsBitNumber
  7. {
  8.     static void Main()
  9.     {
  10.         // Declaring needed variables
  11.         int number;
  12.         int position;
  13.         int mask;
  14.         int result;
  15.         bool isValid;
  16.  
  17.         // Making validation
  18.         do
  19.         {
  20.             Console.Write("Enter a number: ");
  21.             isValid = int.TryParse(Console.ReadLine(), out number);
  22.         }
  23.         while (number < 2147483647 | number > 0 && isValid == false);
  24.         do
  25.         {
  26.             Console.Write("Enter the position: ");
  27.             isValid = int.TryParse(Console.ReadLine(), out position);
  28.         }
  29.         while (position < 99 | position > 0 && isValid == false);
  30.  
  31.         // Taking the number accordingly the position
  32.         mask = 1 << position;
  33.         result = mask & number;
  34.         result = result >> position;
  35.  
  36.         // Print on the console
  37.         Console.WriteLine("At the position {0} of the binary representation of number {1} is digit: {2}", position, number, result);
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement