settingsAccountsettings
Menusettings

Q: Bitwise task in C#: Modify a Bit at Given Position

+4 votes

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:

modify a bit at given position - bitwise task in C#

asked in C# category by user ak47seo
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

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)");
        }
    }
}
answered by user richard8502
selected by user ak47seo
Good! thanks
...