ellapt

3.12.SetTheBit

Dec 18th, 2012
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. using System;
  2.  
  3. class SetTheBit
  4. {
  5. static void Main()
  6. {
  7. Console.WriteLine( "Given integer number n, value v (0 or 1) and position p.");
  8. Console.WriteLine("Modify n to hold value v at position p from the binary representation of n.");
  9. //Example: n = 5 (00000101), p=3, v=1  13 (00001101) n = 5 (00000101), p=2, v=0  1 (00000001) */
  10.  
  11. bool checkInput1, checkInput2, checkInput3;
  12. int numN; // the number to set bit of
  13. int newN=0; // the result
  14. byte posP; // bit position and
  15. int valueV; // the value to initialize the mask
  16. int maskM; // the mask
  17.  
  18. Console.Write("Please, enter an integer number to set a bit of: ");
  19. string inputInt = Console.ReadLine();
  20. checkInput1 = int.TryParse(inputInt, out numN);
  21.  
  22. Console.Write("Please, enter the number of bit (0-31): ");
  23. inputInt = Console.ReadLine();
  24. checkInput3 = (byte.TryParse(inputInt, out posP));
  25.  
  26. Console.Write("Please, enter the value (0 or 1): ");
  27. inputInt = Console.ReadLine();
  28. checkInput2 = (int.TryParse(inputInt, out valueV));
  29.  
  30. if (checkInput1 && checkInput2 && checkInput3 && valueV <= 1 && posP < 32)
  31. {
  32.  
  33. if (valueV == 1)
  34. {
  35. maskM=valueV << posP; // shift left the bit to receive the mask
  36. newN = numN | maskM; // OR the number with the mask
  37. }
  38. else
  39. {
  40. maskM= 1 << posP; // first set the bit to 1, then shift left
  41. newN = numN & (~maskM); // bit AND the number with the 1st complement of the mask
  42. }
  43.  
  44. Console.WriteLine("The bit {0} of the integer number {1} (HexDec {1:X}) is set to {2} ", posP, numN, valueV);
  45. Console.WriteLine("Now this integer number is: {0} (HexDec {0:X}) ", newN);
  46. }
  47. else
  48. {
  49. Console.WriteLine("Wrong data!");
  50. }
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment