3
22/10/2024 2:16 pm
Topic starter
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.
Examples:
1 Answer
3
22/10/2024 2:17 pm
Here's my answer:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class ModifyABitAtGivenPosition { static void Main() { Console.Write("Enter n (your number): "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter p (position of the bit to change): "); int p = int.Parse(Console.ReadLine()); Console.Write("Enter v: zero or one (your bit to change): "); int v = int.Parse(Console.ReadLine()); if (v == 1) { int mask = 1 << p; int result = mask | n; Console.WriteLine("the RESULT in decimal:{0}", result); Console.WriteLine("the NUMBER:" + Convert.ToString(n, 2).PadLeft(32, '0')); Console.WriteLine(" the MASK:" + Convert.ToString(mask, 2).PadLeft(32, '0')); Console.WriteLine("the RESULT:" + Convert.ToString(result, 2).PadLeft(32, '0')); } else if (v == 0) { int mask = ~(1 << p); int result = mask & n; Console.WriteLine("the RESULT in decimal:{0}", result); Console.WriteLine("the NUMBER:" + Convert.ToString(n, 2).PadLeft(32, '0')); Console.WriteLine(" the MASK:" + Convert.ToString(mask, 2).PadLeft(32, '0')); Console.WriteLine("the RESULT:" + Convert.ToString(result, 2).PadLeft(32, '0')); } else if (v != 1 || v != 0) { Console.WriteLine("WRONG! Please write for v: (0) or (1)"); } } }