Advertisement
dimipan80

3.15 Bits Exchange

Jun 5th, 2014
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.66 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.  
  3. namespace _15.BitsExchange
  4. {
  5.     using System;
  6.  
  7.     public class BitsExchange
  8.     {
  9.         public static void Main(string[] args)
  10.         {
  11.             checked
  12.             {
  13.                 Console.Write("Enter a whole 32-bits non-negative number: ");
  14.                 uint num = uint.Parse(Console.ReadLine());
  15.  
  16.                 // First checking bit values on given positions. If founded bit values is equals, the exchange does not necessary and given number is output result.
  17.                 long bitValueOn543 = ((long)num >> 3) & 7;
  18.                 long bitValueOn262524 = ((long)num >> 24) & 7;
  19.                 uint resultNum = num;
  20.                 if (bitValueOn543 != bitValueOn262524)
  21.                 {
  22.                     // Now must nullifying bits on given positions:
  23.                     long bitMask543 = bitValueOn543 << 3;
  24.                     resultNum = (uint)(num ^ bitMask543);
  25.                     long bitMask262524 = bitValueOn262524 << 24;
  26.                     resultNum ^= (uint)bitMask262524;
  27.  
  28.                     // Exchages the bits on positions 3, 4 and 5:
  29.                     long bitMaskExchange543 = bitValueOn262524 << 3;
  30.                     resultNum |= (uint)bitMaskExchange543;
  31.  
  32.                     // Exchanges the bits on positions 24, 25 and 26:
  33.                     long bitMaskExchange262524 = bitValueOn543 << 24;
  34.                     resultNum |= (uint)bitMaskExchange262524;
  35.                 }
  36.  
  37.                 Console.WriteLine("The Number After Bits Exchange is: {0} !", resultNum);
  38.             }
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement