Venciity

BitWiseOperators - get the bit at position p in number

Jan 30th, 2014
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.66 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ex1
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             // get the bit at position (p) in number (n)
  14.             int p = 3;                  
  15.             int n = 42;                 //00101010
  16.             int shifted = (n >> p);     //00000101
  17.             int result = shifted & 1;   //00000001
  18.             Console.WriteLine(result);  //1
  19.  
  20.             // съкратен вариант
  21.             //int result = ((n >> p) & 1);
  22.             //Console.WriteLine(result);
  23.         }
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment