简体   繁体   中英

Operators and Expressions Problem that I can not solve in C#

We are given the number n, the value v (v = 0 or 1) and the position p. write a sequence of operations that changes the value of n, so the bit on the position p has the value of v. Example: n=35, p=5, v=0 -> n=3. Another example: n=35, p=2, v=1 -> n=39.

I am unable to find a way to only use that bit on the position p.

If i do n >> p with a number such as 35 in bits I will have 100011 >> 5 = 00001

I don't know how to get the value of v here. Mathematically even if I think about it above the value of n becomes 1 not 3 after this operation. I am totally confused as I can not explain the problem to myself.

  Console.Write("Enter n: ");
    int n = Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter p: ");
    int p = Convert.ToInt32(Console.ReadLine());
    Console.Write("Enter v: ");
    int v = Convert.ToInt32(Console.ReadLine());
    int mask = n >> 5;
    Console.WriteLine(mask);

I would take this approach:

  • Work out the shifted value of the bit using the << operator
  • If v is 1, set the bit using |
  • Otherwise, clear it using & (and ~ for bitwise negation to create a mask)

So something like:

int shifted = 1 << p;

if (v == 1)
{
    n |= shifted; // Set the bit 
}
else
{
    // Clear the bit, by masking with the bitwise inverse  of the shifted value
    n &= ~shifted;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM