Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class ExchangeBits
- {
- static void Main()
- {
- Console.WriteLine("This program exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given\n32-bit unsigned integer.\n");
- Console.Write("Please insert a positive integer number: ");
- uint controlNumber = uint.Parse(Console.ReadLine());
- uint resultNumber = controlNumber;
- byte firstBitPosition = 3;
- byte secondBitPosition = 24;
- for (byte i = 0; i < 3; i++, firstBitPosition++, secondBitPosition++)
- {
- uint secondTempVariable;
- uint firstTempVariable;
- uint firstBit;
- uint secondBit;
- uint mask = 1u;
- //Finding the value of the bit on position firstBitPosition (3,4,5)
- mask <<= firstBitPosition;
- firstBit = (mask & controlNumber);
- firstBit >>= firstBitPosition;
- //Finding the value of the bit on position secondBitPosition (24,25,26)
- mask = (1u << secondBitPosition);
- secondBit = (mask & controlNumber);
- secondBit >>= secondBitPosition;
- //Setting the value of bit firstBitPosition to position secondBitPosition
- if (firstBit == 1)
- {
- mask = 1u << secondBitPosition;
- secondTempVariable = resultNumber | mask;
- }
- else
- {
- mask = ~(1u << secondBitPosition);
- secondTempVariable = resultNumber & mask;
- }
- firstTempVariable = secondTempVariable;
- //Setting value of bit secondBitPosition to position firstBitPosition
- if (secondBit == 1)
- {
- mask = 1u << firstBitPosition;
- resultNumber = (firstTempVariable | mask);
- }
- else
- {
- mask = ~(1u << firstBitPosition);
- resultNumber = firstTempVariable & mask;
- }
- }
- Console.WriteLine("\nThe new number is {0}.\n", resultNumber);
- Console.WriteLine(controlNumber + " - " + Convert.ToString(controlNumber, 2).PadLeft(32, '0'));
- Console.WriteLine(resultNumber + "-" + Convert.ToString(resultNumber, 2).PadLeft(32, '0'));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement