ellapt

3.14.SwapBitSequences

Dec 18th, 2012
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. using System;
  2.  
  3. class SwapBitSequences
  4. {
  5. static void Main()
  6. {
  7. Console.WriteLine("Exchange bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.");
  8.  
  9. int p; // position of bit sequence 1 to swap
  10. int q; // position of bit sequence 2 to swap
  11. int k; // number of consecutive bits in each sequence
  12. uint numN; // the number whose bits are to be swapped
  13. uint newN; // the bit-swapped number
  14.  
  15. bool checkInput1, checkInput2, checkInput3, checkInput4;
  16.  
  17. Console.Write("Please, enter the position of the first set of bits to be swapped (unsigned integer): ");
  18. string inputInt = Console.ReadLine();
  19. checkInput1 = int.TryParse(inputInt, out p);
  20.  
  21. Console.Write("Please, enter the position of the second set of bits to be swapped (unsigned integer): ");
  22. inputInt = Console.ReadLine();
  23. checkInput2 = int.TryParse(inputInt, out q);
  24.  
  25. Console.Write("Please, enter the number of bits to be swapped: ");
  26. inputInt = Console.ReadLine();
  27. checkInput3 = (int.TryParse(inputInt, out k));
  28.  
  29. Console.Write("Please, enter an unsigned integer number to swap the bits of: ");
  30. inputInt = Console.ReadLine();
  31. checkInput4 = uint.TryParse(inputInt, out numN);
  32.  
  33. if (checkInput1 && checkInput2 && checkInput3 && checkInput4)
  34. {
  35. if (k != 0 && (Math.Abs(q - p) > k) && (Math.Max(q, p) + k < 32))
  36. {
  37. uint workVar = ((numN >> p) ^ (numN >> q)) & (~(1U << k)); // XOR temporary variable
  38. newN = numN ^ ((workVar << p) | (workVar << q));
  39. Console.WriteLine("The unsigned integer number was: {0} (HexDec {0:X})", numN);
  40. Console.WriteLine("The result is: {0} (HexDec {0:X}) ", newN);
  41. }
  42. else
  43. {
  44. Console.WriteLine("Bit sequiences overlap, or exceed the length of uint, or 0 sequence!");
  45. }
  46. }
  47. else
  48. {
  49. Console.WriteLine("Wrong input!");
  50. }
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment