Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class ExchangeBitAtPositionInIntNum
- {
- static void Main()
- {
- //We are given integer number n, value v (v=0 or 1) and a position p. Write a sequence of operators that modifies n to hold the value v at the position p from the binary representation of n.
- //Example: n = 5 (00000101), p=3, v=1 =>13 (00001101)
- // n = 5 (00000101), p=2, v=0 => 1 (00000001)
- Console.Write("Enter an integer number:");
- int numberToModify = int.Parse(Console.ReadLine());
- Console.Write("Enter a position to modify (0 to 31):");
- int positionToModify = int.Parse(Console.ReadLine());
- Console.Write("Enter a value to change (0 or 1):");
- int valueToModify = int.Parse(Console.ReadLine());
- int modifiedNumber;
- if (valueToModify == 0)
- modifiedNumber = (~(1 << positionToModify) & numberToModify);
- else
- modifiedNumber = ((1 << positionToModify) | numberToModify);
- Console.WriteLine("The number to modify is: {0}", Convert.ToString(numberToModify,2).PadLeft(32, '0'));
- Console.WriteLine("The position to modify is: {0}", positionToModify);
- Console.WriteLine("The value to modify with is: {0}", valueToModify);
- Console.WriteLine("The modified number is: {0}", Convert.ToString(modifiedNumber, 2).PadLeft(32, '0'));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement