Advertisement
stkirov

14.ExchangeBits

Oct 9th, 2012
523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class Program
  5. {
  6.     static void Main()
  7.     {
  8.         uint n = 4290772963;
  9.  
  10.         //Print the number before it has been changed for comparison
  11.         Console.WriteLine(Convert.ToString(n, 2));
  12.  
  13.         byte p = 3;
  14.         byte q = 2;
  15.         byte k = 21;
  16.         uint mask = 1;//when shifting right you need yout right side to be int
  17.  
  18.         //set the mask E.g (2^3) - 1
  19.         for (int i = 0; i < p; i++)
  20.         {
  21.             mask *= 2;
  22.         }
  23.  
  24.         //get the first bits
  25.         uint getFirstBits = (((mask - 1) << q) & n) >> q;
  26.         //get the second bits
  27.         uint getSecondBits = (((mask - 1) << k) & n) >> k;
  28.  
  29.         //null the first bits
  30.         n = n & (~((mask - 1) << q));
  31.         //null the second bits
  32.         n = n & (~((mask - 1) << k));
  33.  
  34.         //we concatnate the first bits and the nulled number(we exchange them)
  35.         n = n | (getFirstBits << k);
  36.  
  37.         //we concatnate the second bits and the nulled number(we exchange them)
  38.         n = n | (getSecondBits << q);
  39.  
  40.         //Print changed
  41.         Console.WriteLine(Convert.ToString(n, 2));
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement