Advertisement
VyaraG

BitOperators

Dec 16th, 2014
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. //https://www.youtube.com/watch?v=8vxQqbFGW-E --> exchange of bits on a guiven position (39:51)
  2. using System;
  3.  
  4. class BitwiseOperators
  5. {
  6.     static void Main()
  7.     {
  8.         ushort a = 3;                  // 00000000 00000011 = 3
  9.         ushort b = 5;                  // 00000000 00000101 = 5
  10.  
  11.         Console.WriteLine( a | b);     // 00000000 00000111 = 7
  12.         Console.WriteLine( a & b);     // 00000000 00000001 = 1
  13.         Console.WriteLine( a ^ b);     // 00000000 00000110 = 6
  14.         Console.WriteLine(~a & b);     // 00000000 00000100 = 4
  15.         Console.WriteLine( a << 1 );   // 00000000 00000110 = 6
  16.         Console.WriteLine( a >> 1 );   // 00000000 00000001 = 1
  17.         Console.WriteLine( a >> 2 );   // 00000000 00000000 = 0
  18.         Console.WriteLine( a << 2 );   // 00000000 00001100 = 12
  19.         Console.WriteLine(~a);         // 11111111 11111100 = -4 = 65532
  20.         Console.WriteLine((ushort)~a); // 11111111 11111100 = -4 = 65532
  21.  
  22.         // Find the bit at position p in n
  23.         int p = 5;
  24.         int n = 291;               // 00000001 00100011
  25.         int nRightP = n >> p;      // 00000000 00001001
  26.         int bit = nRightP & 1;     // 00000000 00000001
  27.         Console.WriteLine(bit);    // 1
  28.  
  29.         // Set the bit at position p to 0 in a number n
  30.         p = 5;
  31.         n = 291;                   // 00000001 00100011
  32.         int mask = ~(1 << p);      // 11111111 11011111
  33.         int result = n & mask;     // 00000001 00000011
  34.         Console.WriteLine(result); // 259
  35.         Console.WriteLine(Convert.ToString(result, 2).PadLeft(16, '0'));
  36.  
  37.         p = 4;
  38.         n = 291;                   // 00000001 00100011
  39.         mask = 1 << p;             // 00000000 00010000
  40.         result = n | mask;         // 00000001 00110011
  41.         Console.WriteLine(result); // 307
  42.         Console.WriteLine(Convert.ToString(result, 2).PadLeft(16, '0'));
  43.  
  44.         //check the bit and take it
  45.  
  46.         int mask = 1<<position;
  47.         int result = mask & n;
  48.         result = result >> position;
  49.  
  50.     //take the third bit
  51.     int mask = 1<<3;
  52.     int thirdBit = (n&mask)>>3;
  53.  
  54.  
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement