Advertisement
remote87

Modify a Bit at Given Position

Aug 30th, 2015
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.07 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace _14ModifyBitAtGivenPosition
  8. {
  9.     class ModifyBitAtGivenPosition
  10.     {
  11.         static void Main()
  12.         {
  13.             for (int i = 0; i < 5; i++)
  14.             {
  15.                 Console.Write("Enter a number: ");
  16.                 int number = int.Parse(Console.ReadLine());
  17.                 Console.Write("Enter a position for the bit: ");
  18.                 int p = int.Parse(Console.ReadLine());
  19.                 Console.Write("Enter a bit value ( 0/1 ): ");
  20.                 int v = int.Parse(Console.ReadLine());
  21.                 if (v == 1)
  22.                 {
  23.                     int mask = 1 << p;
  24.                     int result = number | mask;
  25.                     Console.WriteLine(result);
  26.                 }
  27.                 else
  28.                 {
  29.                     int mask = ~(1 << p);
  30.                     int result = number & mask;
  31.                     Console.WriteLine(result);
  32.                 }
  33.             }
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement