How to toggle a bit at specific position in C#

1 Answer

0 votes
using System;

class Program
{
    static void print_bits(int n, int width = 8) {
        Console.WriteLine(Convert.ToString(n, 2).PadLeft(width, '0'));
    }

    static void Main()
    {
        int n = 365, pos = 2;

        print_bits(n); // default: 8 bits

        n ^= (1 << pos);

        print_bits(n);
    }
}


/*
run:
      
101101101
101101001
   
*/

 



answered Mar 20, 2019 by avibootz
edited Apr 2 by avibootz
...