Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Write a program that exchanges bits {p, p+1, …, p+k-1} with bits {q, q+1, …, q+k-1} of a given 32-bit unsigned integer. The first and the second sequence of bits may not overlap.
- namespace _16.BitExchange_Advanced
- {
- using System;
- public class BitExchange_Advanced
- {
- public static void Main(string[] args)
- {
- checked
- {
- Console.Write("Enter a whole 32-bits non-negative number: ");
- uint num = uint.Parse(Console.ReadLine());
- Console.Write("Enter index for start position of First Bit-sequence: ");
- int indexP = int.Parse(Console.ReadLine());
- Console.Write("Enter index for start position of Second Bit-sequence: ");
- int indexQ = int.Parse(Console.ReadLine());
- Console.Write("Enter a whole positive number for lenght of Bit-sequences: ");
- uint lenghtK = uint.Parse(Console.ReadLine());
- bool inputDataIsOutOfRange = (indexP < 0 || indexP + lenghtK - 1 > 31) || (indexQ < 0 || indexQ + lenghtK - 1 > 31) || lenghtK > 16;
- if (!inputDataIsOutOfRange)
- {
- bool bitSequncesOverlapping = (indexQ > indexP && indexP + lenghtK - 1 >= indexQ) || (indexP > indexQ && indexQ + lenghtK - 1 >= indexP) || indexP == indexQ;
- if (!bitSequncesOverlapping)
- {
- // First checking bit values on Bit Sequences. For this we needs from bit mask for all bits in the Sequence. That is depends from lenghtK:
- long bitMaskLenght = (long)((1 << (int)lenghtK) - 1);
- // Getting bit values from First Sequence:
- long bitValuesOnFirstSequence = ((long)num >> indexP) & bitMaskLenght;
- // Getting bit values from Second Sequence:
- long bitValuesOnSecondSequence = ((long)num >> indexQ) & bitMaskLenght;
- // If founded bit values is equals, the exchange does not necessary and given number is output result.
- uint resultNum = num;
- if (bitValuesOnFirstSequence != bitValuesOnSecondSequence)
- {
- // Now must nullifying bits on given positions:
- long bitMaskOnFirstSeq = bitValuesOnFirstSequence << indexP;
- resultNum = (uint)(num ^ bitMaskOnFirstSeq);
- long bitMaskOnSecondSeq = bitValuesOnSecondSequence << indexQ;
- resultNum ^= (uint)bitMaskOnSecondSeq;
- // Exchages the bits on positions of First Sequence:
- long bitMaskExchangeFirstSeq = bitValuesOnSecondSequence << indexP;
- resultNum |= (uint)bitMaskExchangeFirstSeq;
- // Exchages the bits on positions of Second Sequence:
- long bitMaskExchangeSecondSeq = bitValuesOnFirstSequence << indexQ;
- resultNum |= (uint)bitMaskExchangeSecondSeq;
- }
- Console.WriteLine("The Number After Bits Exchange is: {0} !", resultNum);
- }
- else
- {
- Console.WriteLine("Error! - BitSequences on these Positions Overlapping!!!");
- }
- }
- else
- {
- Console.WriteLine("Error!!! - Input Data is Out of Range!!!");
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement