Skip to content

Instantly share code, notes, and snippets.

@dentia dentia/BOTask
Created Jan 12, 2015

Embed
What would you like to do?
//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.
namespace BitExchange_Advances
{
using System;
class BitExchange_Advances
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
long number = long.Parse(Console.ReadLine());
Console.Write("Enter position P: ");
int p = int.Parse(Console.ReadLine());
Console.Write("Enter position Q: ");
int q = int.Parse(Console.ReadLine());
Console.Write("Enter length K: ");
int k = int.Parse(Console.ReadLine());
for (int firstIndices = p, secondIndices = q, length = k;
(firstIndices <= 32 && secondIndices <= 32) && length > 0;
firstIndices++, secondIndices++, length--)
{
if (((number >> firstIndices) & 1) != ((number >> secondIndices) & 1))
{
number = changeBits(number, firstIndices, secondIndices);
}
}
Console.WriteLine("Result: " + number);
}
private static long changeBits(long number, int firstposition, int secondPosition)
{
number ^= (1 << firstposition);
return number ^ (1 << secondPosition);
}
}
}
/*
for ex.
*
* 111 in binary is 1101111
* if p=3, q=10, k=3, we exchange 3 with 10, 4 with 11 and 5 with 12
* we get 1010001000111 or 5191 in dec
*
*
* |12|11|10|09|08|07|06|05|04|03|02|01|00|
* ----------------------------------------
* | 0| 0| 0| 0| 0| 0| 1| 1| 0| 1| 1| 1| 1|
* | 1| 0| 1| 0| 0| 0| 1| 0| 0| 0| 1| 1| 1|
*/
@SimoPrG

This comment has been minimized.

Copy link

SimoPrG commented Jan 17, 2015

I think according to the condition of the problem you should declare number as int and also line 21 should look like this:
(firstIndices < 32 && secondIndices < 32) && length > 0;
firstIndices <=32 and secondIndices <= 32 will wrap around because the bit indexes are from 0 to 31.
Best Regards,
Simo

P.S. Sorry if I am getting annoying. I just like to improve stuff :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.