Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- // 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)
- class HoldValuePositionBinary
- {
- static void Main()
- {
- Console.Write("Enter n = ");
- int n = int.Parse(Console.ReadLine()); // number
- Console.Write("Enter v = ");
- int v = int.Parse(Console.ReadLine()); // v = 1 or 0
- Console.Write("Enter p = ");
- int p = int.Parse(Console.ReadLine()); // position
- int bit = 0;
- int mask = 1;
- bit = mask << p;
- bit = (n & bit) >> p;
- if (bit != v) // if (bit != v)
- {
- bit = mask << p;
- n ^= bit;
- Console.WriteLine(n);
- }
- else // if (bit = v)
- {
- bit = mask << p;
- n |= bit;
- Console.WriteLine(n);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement