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 given 32-bit unsigned integer.
- */
- using System;
- class ExchangeOfBitsRandomPositions
- {
- static void Main()
- {
- uint number;
- int i,j, p, q, k, jp, jq;
- long valueBitPosition, valueBitPositionP, valueBitPositionQ;
- int[] bitValue = new int[32];
- int[] newBitValueP = new int[32];
- int[] newBitValueQ = new int[32];
- Console.WriteLine("Enter number > 0: ");
- while (!(uint.TryParse(Console.ReadLine(), out number)))
- {
- Console.WriteLine("Enter number > 0: ");
- }
- Console.WriteLine("Enter amount of bits you want to change k: ");
- while (!(int.TryParse(Console.ReadLine(), out k)))
- {
- Console.WriteLine("Enter amount of bits you want to change k: ");
- }
- Console.WriteLine("Enter start position p: ");
- while (!(int.TryParse(Console.ReadLine(), out p)))
- {
- Console.WriteLine("Enter start position p: ");
- }
- Console.WriteLine("Enter end position q: ");
- while (!(int.TryParse(Console.ReadLine(), out q) && q > k+p))
- {
- Console.WriteLine("Enter end position q (q > k+p): ");
- }
- for (i = 0; i <= 31; i++)
- {
- valueBitPosition = ((1 << i) & number);
- if (valueBitPosition == 0)
- {
- bitValue[i] = 0;
- }
- else
- {
- bitValue[i] = 1;
- }
- }
- for (jp = p, jq = q, j = 0; j < k; jp++, jq++, j++)
- {
- valueBitPositionP = (((1 << jp) & number)) >> jp;
- valueBitPositionQ = (((1 << jq) & number)) >> jq;
- if (valueBitPositionP != valueBitPositionQ)
- {
- newBitValueP[jp] = bitValue[jq];
- newBitValueQ[jq] = bitValue[jp];
- bitValue[jp] = newBitValueP[jp];
- bitValue[jq] = newBitValueQ[jq];
- }
- }
- Array.Reverse(bitValue);
- Console.WriteLine(Convert.ToString(number, 2).PadLeft(32, '0'));
- //Console.WriteLine(bitValue.Length);
- for (j = 0; j <= 31; j++)
- {
- Console.Write(bitValue[j]);
- }
- Console.WriteLine("\n");
- Main();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment