Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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)
- */
- using System;
- class ModifyNumberBits
- {
- static void Main()
- {
- int numberN, valueV, positionP, numberMask, modifiedNumber;
- string errorInvalidInt = "Invalid input! Please enter number between " + int.MinValue + " and " + int.MaxValue + "!\n";
- Console.WriteLine("Enter integer number: ");
- if (int.TryParse(Console.ReadLine(), out numberN) && numberN >= int.MinValue && numberN <= int.MaxValue)
- {
- Console.WriteLine("Binary code of your number {0} is: {1}", numberN, Convert.ToString(numberN, 2).PadLeft(32, '0'));
- Console.WriteLine("Enter bit position you want to modify (count from 0): ");
- if (int.TryParse(Console.ReadLine(), out positionP) && positionP >= int.MinValue && positionP <= int.MaxValue)
- {
- Console.WriteLine("Enter value V (0 or 1): ");
- while (!(int.TryParse(Console.ReadLine(), out valueV) && (valueV == 0 || valueV == 1)))
- {
- Console.WriteLine("Enter value V (0 or 1): ");
- }
- if (valueV == 0)
- {
- numberMask = ~(1 << positionP);
- modifiedNumber = numberN & numberMask;
- }
- else
- {
- numberMask = 1 << positionP;
- modifiedNumber = numberN | numberMask;
- }
- Console.WriteLine("{0}: \t{1}\n{2}: \t{3}\n", numberN, Convert.ToString(numberN, 2).PadLeft(32, '0'), modifiedNumber, Convert.ToString(modifiedNumber, 2).PadLeft(32, '0'));
- Main();
- }
- else
- {
- Console.WriteLine(errorInvalidInt);
- Main();
- }
- }
- else
- {
- Console.WriteLine(errorInvalidInt);
- Main();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment