ellapt

3.11.ExtractBit

Dec 14th, 2012
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. using System;
  2.  
  3. class ExtractBit
  4. {
  5. static void Main()
  6. {
  7. bool checkInput1, checkInput2;
  8. int extractBitB;
  9. int i; // the number to extract from
  10. int b; // byte position;
  11. int bitMaskP = 1; // initialize the mask
  12. byte theBit=1;
  13.  
  14. Console.WriteLine("Extract from a given integer i the value of a given bit number b.");
  15. Console.WriteLine("Please, enter an integer number to extract a bit from: ");
  16. string inputInt = Console.ReadLine();
  17. checkInput1 = int.TryParse(inputInt, out i);
  18. Console.WriteLine("Please, enter the number of bit (0-31): ");
  19. inputInt = Console.ReadLine();
  20. checkInput2 = (int.TryParse(inputInt, out b));
  21. if (checkInput1 && checkInput2 && b < 32)
  22. {
  23. for (int j = 0; j < b; j++)
  24. {
  25. bitMaskP = bitMaskP << 1; //shift the mask b positions to the left;
  26. }
  27. extractBitB = i & bitMaskP;
  28. if(extractBitB==0)
  29. {
  30. theBit=0;
  31. }
  32. Console.WriteLine("The extracted bit {0} of the integer number {1} (HexDec {1:X}) is : {2} ", b, i, theBit);
  33. }
  34. else
  35. {
  36. Console.WriteLine("Wrong data!");
  37. }
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment