Advertisement
Gesh4o

BitWise

Sep 16th, 2015
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. using System;
  2.  
  3. class BitsExchange
  4. {
  5. static void Main()
  6. {
  7. //Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
  8. //First I read the number from the console
  9. Console.Write("Please insert an integer: ");
  10. uint n = uint.Parse(Console.ReadLine());
  11.  
  12. //Then I get the neeeded bits 1 by 1 so I can exchange them later
  13. uint bit3 = n >> 3;
  14. bit3 = bit3 & 1;
  15. uint bit4 = n >> 4;
  16. bit4 = bit4 & 1;
  17. uint bit5 = n >> 5;
  18. bit5 = bit5 & 1;
  19. //Console.WriteLine("{0}{1}{2}",bit5, bit4, bit3);
  20. uint bit24 = n >> 24;
  21. bit24 &= 1;
  22. uint bit25 = n >> 25;
  23. bit25 &= 1;
  24. uint bit26 = n >> 26;
  25. bit26 &= 1;
  26. //Console.WriteLine("{0}{1}{2}", bit26, bit25, bit24);
  27.  
  28. //Now that I have every bit seperately I will try to exchange their positions while the their names(variables) won't be changed
  29. uint mask0 = bit3<<24;
  30. n = (uint)(n &(~(1<<24)));
  31. uint result = mask0 ^ n;
  32.  
  33. uint mask1 = bit4<<25;
  34. n = (uint)(n&(~(1<<25)));
  35. result = mask1 ^ n;
  36.  
  37. uint mask2 = bit5 << 26;
  38. n = (uint)(n & (~(1 << 26)));
  39. result = mask2 ^ n;
  40.  
  41. //Now I have transfered bits at poistion 3,4 and 5 to 24,25 and 26 so I have to the the same but backwards
  42. uint mask3 = bit24 << 3;
  43. n = (uint)(n & (~(1 << 3)));
  44. result = result & mask3;
  45.  
  46. uint mask4 = bit25 << 4;
  47. n = (uint)(n & (~(1 << 4)));
  48. result = result ^ mask4;
  49.  
  50. uint mask5 = bit26 << 5;
  51. n = (uint)(n & (~(1 << 5)));
  52. result = result ^ mask5;
  53.  
  54. Console.WriteLine(result);
  55.  
  56.  
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement