Advertisement
stkirov

13.ExchangeBits

Nov 3rd, 2012
570
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.16 KB | None | 0 0
  1. //Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
  2. using System;
  3. using System.Collections.Generic;
  4.  
  5. class Program
  6. {
  7.     static void Main()
  8.     {
  9.         int n = 2147418112; //for easier exchange watch
  10.         int mask = 7;
  11.         int getFirstBits = (7 << 3) & n; //get bits 3 4 5
  12.         int getSecondBits = (7 << 24) & n;  //get bits 24 25 26
  13.         getFirstBits = getFirstBits << 21; //push 3, 4, 5 bit, twenty one positions to the left
  14.         getSecondBits = getSecondBits >> 21; //push 24,25,26 bit, twenty one positions to the right
  15.  
  16.         n = n & (~(mask << 3)); //null the 3,4,5 bits for easier concatination
  17.         Console.WriteLine(Convert.ToString(n, 2));
  18.         n = n & (~(mask << 21)); //null the 24,25,26 bits for easier concatination
  19.         Console.WriteLine(Convert.ToString(n, 2));
  20.         n = n | getFirstBits; //concatinate the number and the pushed 3,4,5 bits
  21.         Console.WriteLine(Convert.ToString(n, 2));
  22.         n = n | getSecondBits; //concatinate the number and the pushed 24,25,26 bits
  23.         Console.WriteLine(Convert.ToString(n, 2));
  24.         Console.WriteLine(n);
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement