My Blog

Bitset function in C#

by lupok on mercoledì 23 gennaio 2013 17:19
      /// 
      /// Ottiene il valore di un bit
      /// 
      /// Valore di cui è richiesto il bit
      /// Indice del bit.
      /// True se il bit è 1, false se è 0.
      public static bool Get(int value, byte bit)
      { 
         return (value >> bit & 1) == 1; 
      }
 
      /// 
      /// Imposta ad 1 un bit in un valore.
      /// 
      /// Valore in cui impostare il bit.
      /// Posizione del bit.
      /// Il nuovo valore.
      public static int Set(int value, byte bit)
      { 
         return Set(value, bit, true); 
      }
 
      /// 
      /// Imposta un bit in un valore.
      /// 
      /// Valore in cui variare il bit.
      /// Posizione del bit.
      /// Se True imposta il bit ad 1, se False lo imposta a 0.
      /// Il nuovo valore.
      public static int Set(int value, byte bit, bool on)
      { 
         return on ? value | (1 << bit) : Reset(value, bit); 
      }
 
      /// 
      /// Imposta a 0 un bit in un valore.
      /// 
      /// Valore in cui impostare il bit.
      /// Posizione del bit.
      /// Il nuovo valore.
      public static int Reset(int value, byte bit)
      { 
         return value & ~(1 << bit); 
      }

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags