Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 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. */
- namespace _14.ModifyBitAtGivenPositionInIntegerNumber
- {
- using System;
- public class ModifyBitAtGivenPositionInIntegerNumber
- {
- public static void Main(string[] args)
- {
- checked
- {
- Console.Write("Enter a whole non-negative number: ");
- uint num = uint.Parse(Console.ReadLine());
- int positionP;
- do
- {
- Console.Write("Enter index for Bit position: ");
- }
- while (!int.TryParse(Console.ReadLine(), out positionP) || positionP < 0 || positionP > 31);
- int bitValueToModified;
- do
- {
- Console.Write("Enter value of bit on position P, to modifying: ");
- }
- while (!int.TryParse(Console.ReadLine(), out bitValueToModified) || bitValueToModified < 0 || bitValueToModified > 1);
- // Checking on given position in number bit value:
- int startBitValue = (int)((long)num >> positionP) & 1;
- // Comparing founded bit value and given is equals or not. If bit values is equals, modifying is not necesary and given number is output result.
- uint resultNum = num;
- if (startBitValue != bitValueToModified)
- {
- long bitMask;
- if (startBitValue == 0)
- {
- // Modifying bit value on given position from 0 to 1:
- bitMask = 1 << positionP;
- resultNum = (uint)((long)num | bitMask);
- }
- else
- {
- // Modifying bit value on given position from 1 to 0:
- bitMask = ~(1 << positionP);
- resultNum = (uint)(num & bitMask);
- }
- }
- Console.WriteLine("The number after modifying bit value is: {0} !", resultNum);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement