Advertisement
Booster

Change Bits Integer

Jul 18th, 2014
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3.  
  4. class ChangeBitsInteger
  5. {
  6.     static void Main()
  7.  
  8.     {
  9.     //Must change places between 3rd, 4th, 5th and 24th,25th,26th bit in integer number
  10.         var timer = System.Diagnostics.Stopwatch.StartNew();
  11.  
  12.         Console.Write("Enter a number and see the result of\n changing 3,4,5bit with 24,25,26bit: ");
  13.         int num = int.Parse(Console.ReadLine());
  14.         //Bits 3-24, 4-25, 5-26    
  15.         //int num Example = 1234567890; //1001'001'100101100000001011'010'010
  16.         int mask3 = 7 << 3; //7 in Binary is 111, 3 positions left to check 3,4,5bit
  17.         int mask3bits = mask3 & num;
  18.         //Bits 3-0; 4-1; 5-0
  19.         int result3 = mask3bits >> 3; //010
  20.  
  21.         int mask24 = 7 << 24; //Check 24,25,26 bit
  22.         int mask24bits = mask24 & num;
  23.         //Bits 24-1, 25-0, 26-0
  24.         int result24 = mask24bits >> 24; //001
  25.         //Move 24,25,26 bits to 3,4,5 position
  26.         int replacebits3to24 = result3 << 24;                  //00'010'000000000000
  27.         //Move 3,4,5 bits to 24,25,26 position
  28.         int replacebits24to3 = result24 << 3;                  //00000000000'001'000
  29.         int resultAll = replacebits24to3 | replacebits3to24;   //00'010'0000'001'000
  30.         int oppositemask3 = ~mask3;                //Opposite mask 11111111111000111
  31.         int oppositemask24 = ~mask24;              //Opposite mask 11100011111111111
  32.         int oppositemaskAll = oppositemask24 & oppositemask3; //General opposite mask 111'000'11111111111111'000'111
  33.         int nummask = oppositemaskAll & num;  //Take values from num to General mask  101'000'01000111010001'000'101
  34.         int finalnumber = nummask | resultAll; //3,4,5bit <=> 24,25,26 bit
  35.         Console.WriteLine("Number \"{0}\", gets: \"{1}\"", num, finalnumber);
  36.  
  37.         var elapsed = timer.ElapsedMilliseconds;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement