Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class BitsExchange_AdvancedTask
- {
- static void Main ()
- {
- checked
- {
- Console.Write("Please, enter a whole non-negative Integer number N = ");
- string numberStr = Console.ReadLine();
- int numberN = int.Parse(numberStr);
- Console.Write("Enter a whole number for a bit position in the range [0...30], P = ");
- numberStr = Console.ReadLine();
- int bitPositionP = int.Parse(numberStr);
- Console.Write("Enter other whole number for a bit position in the range [0...30], Q = ");
- numberStr = Console.ReadLine();
- int bitPositionQ = int.Parse(numberStr);
- Console.Write("Enter a whole number for a count of bit positions in the range [2...31], K = ");
- numberStr = Console.ReadLine();
- int countBitsK = int.Parse(numberStr);
- if ((bitPositionP + countBitsK) > 32 || (bitPositionQ + countBitsK) > 32)
- {
- Console.WriteLine("Error - Invalid Input !!!");
- Console.ReadLine();
- return;
- }
- // Get bits from the number
- int firstSequenceBits = 0;
- int secondSequenceBits = 0;
- for (int i = 0; i < countBitsK; i++)
- {
- if ((numberN & (1 << (bitPositionP + i))) != 0)
- {
- firstSequenceBits |= (1 << i);
- }
- numberN &= ~(1 << (bitPositionP + i));
- if ((numberN & (1 << (bitPositionQ + i))) != 0)
- {
- secondSequenceBits |= (1 << i);
- }
- numberN &= ~(1 << (bitPositionQ + i));
- }
- // Exchange the bits
- numberN |= secondSequenceBits << bitPositionP;
- numberN |= firstSequenceBits << bitPositionQ;
- // Print result
- Console.WriteLine("The result number is NEW NUMBER = {0} !", numberN);
- Console.ReadLine();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement