Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- //We are given an integer number n, a bit value v (v=0 or 1) and a position p. Write a sequence of operators (a few lines of C# code) that modifies n to hold the value v at the position p from the binary representation of n while preserving all other bits in n.
- class ModifyABitAtGivenPosition
- {
- static void Main()
- {
- Console.Write("Enter a number: ");
- int number = int.Parse(Console.ReadLine());
- Console.Write("Enter a bit value (either '1', or '0'): ");
- int bitValue = int.Parse(Console.ReadLine());
- Console.Write ("Enter a number to indicate the position at which the bit is to be exchanged: ");
- int position = int.Parse(Console.ReadLine());
- if (bitValue==0)
- {
- int mask = ~(1 << position);
- int result = (mask & number);
- Console.WriteLine(result);
- }
- else if (bitValue==1)
- {
- int mask = 1 << position;
- int result = number | mask;
- Console.WriteLine(result);
- }
- else
- Console.WriteLine("Incorrect value!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement