Advertisement
milen8204

[C# Basics]Problem 15.* Bits Exchange

Mar 15th, 2014
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | None | 0 0
  1. using System;
  2. /* Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer.
  3.  * Examples:1140867093  01000100 00000000 01000000 00010101 01000010 00000000 01000000 00100101 1107312677 */
  4. class ExchangeBits
  5. {
  6.     static void Main()
  7.     {
  8.         uint number = 0;
  9.  
  10.         do
  11.         {
  12.             Console.Write("Please, enter a number: ");
  13.  
  14.             if (uint.TryParse(Console.ReadLine(), out number))
  15.             {
  16.                 break;
  17.             }
  18.             else
  19.             {
  20.                 Console.WriteLine("You have entered an invalid number! Try again!");
  21.             }
  22.         } while (true);
  23.        
  24.         Console.Clear();
  25.         Console.WriteLine("You entered number \"{0}\" which is binary \"{1}\".", number, Convert.ToString(number,2));
  26.        
  27.         uint[] arrayString = new uint[32];
  28.  
  29.         for (int i = 31; i >= 0; i--)
  30.         {
  31.             uint var = number << i;
  32.             arrayString[31 - i] = var >> 31;
  33.         }
  34.  
  35.         Console.WriteLine("bit #3 = {0}, bit #4 = {1} and bit #5 = {2}", arrayString[3], arrayString[4], arrayString[5]);
  36.         Console.WriteLine("bit #24 = {0}, bit #25 = {1} and bit #26 = {2}", arrayString[24], arrayString[25], arrayString[26]);
  37.         uint temp3 = arrayString[3];
  38.         uint temp4 = arrayString[4];
  39.         uint temp5 = arrayString[5];
  40.  
  41.         arrayString[3] = arrayString[24];
  42.         arrayString[4] = arrayString[25];
  43.         arrayString[5] = arrayString[26];
  44.  
  45.         arrayString[24] = temp3;
  46.         arrayString[25] = temp4;
  47.         arrayString[26] = temp5;
  48.  
  49.         Console.WriteLine("new bit #3 = {0}, new bit #4 = {1} and new bit #5 = {2}", arrayString[3], arrayString[4], arrayString[5]);
  50.         Console.WriteLine("new bit #24 = {0}, new bit #25 = {1} and new bit #26 = {2}", arrayString[24], arrayString[25], arrayString[26]);
  51.         string result = "";
  52.  
  53.         for (int i = 31; i >= 0; i--)
  54.         {
  55.             result = result + arrayString[i];
  56.         }
  57.  
  58.         uint resultDec = Convert.ToUInt32(result, 2);
  59.  
  60.         Console.WriteLine("result is \"{0}\" which is number \"{1}\".", result, resultDec);
  61.  
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement