Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class ModifyABitAtGivenPosition
- {
- static void Main()
- {
- Console.WriteLine("Enter integer number: ");
- int num = int.Parse(Console.ReadLine());
- Console.WriteLine("Enter bit value: ");
- int value = new int();
- for (int cnt = 0; cnt < 1; cnt++)
- {
- value = int.Parse(Console.ReadLine());
- if (value < 0 && value > 1)
- {
- Console.WriteLine("Invalid Input (only 1 and 0 are allowed). Try Again.");
- cnt--;
- }
- }
- Console.WriteLine("Enter bit position [0-n]: ");
- int position = int.Parse(Console.ReadLine());
- //-------------------------
- bool checkBitValue = ((num >> position) & 1) == 1;
- if (checkBitValue && value == 0)
- {
- num -= (1 << position);
- }
- else
- {
- if (value == 1)
- {
- num += (1 << position);
- }
- }
- Console.WriteLine(num);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment