Opérations sur quartets

Concaténer deux quartets en un octet

byte q1 = 0xc0;
byte q2 = 0x03;
Console.WriteLine("Q1 = 0x" + q1.ToString("X2"));
Console.WriteLine("Q1 = 0x" + q2.ToString("X2"));
Console.WriteLine();

byte b =(byte)(q1 | q2);
Console.WriteLine("Q1 | Q2 = 0x" + b.ToString("X2") + " (B)");
Console.WriteLine();

// Affiche:
// Q1 = 0xC0
// Q2 = 0x03
// Q1 | Q2 = 0xC3

Extraire un quartet

Premier quartet (poids fort, le plus à gauche)

Si on veut obtenir 0xC0 à partir de 0xC3:

byte b = 0xC3;
Console.WriteLine("0x" + b.ToString("X2") + " & 0xF0 = 0x" + (b & 0xF0).ToString("X2")); 

// Affiche:
// 0xC3 & 0xF0 = 0xC0

Si on veut obtenir 0x0C à partir de 0xC3:

byte b = 0xC3;
Console.WriteLine("0x" + b.ToString("X2") + " >> 4 = 0x" + (b >> 4).ToString("X2"));

// Affiche:
// 0xC3 >> 4 = 0x0C

Deuxième quartet (poids faible, le plus à droite)

byte b = 0xC3;
Console.WriteLine("0x" + b.ToString("X2") + " & 0x0F = 0x" + (b & 0x0F).ToString("X2")); 

// Affiche:
// 0xC3 & 0x0F = 0x03

Opérations sur flags

Bien qu'on utilise plus souvent ces opérations sur des enum, je garde la représentation hexadécimale pour ces exemples.

Activer un groupe de bits (OR)

(similaire au premier exemple)

byte b= 0x04; // 0100
byte bits = 0x03; // 0011
Console.WriteLine("0x" + b.ToString("X2") + " | " + "0x" + bits.ToString("X2") + " = 0x" + (b | bits)); // 0111

// Affiche:
// 0x04 | 0x03 = 0x07

Désactiver un groupe de bits (AND NOT)

byte b= 0x07; // 0111
byte bits = 0x03; // 0011
Console.WriteLine("0x" + b.ToString("X2") + " & ~0x" + bits.ToString("X2") + " = 0x" + (b &  ~bits)); // 0100

// Affiche:
// 0x07 & ~0x03 = 0x04

Inverser un groupe de bits (XOR)

Celui-là, il est facile à retenir!

byte b= 0x04; // 0100
byte bits = 0x03; // 0011
Console.WriteLine("0x" + b.ToString("X2") + " ^ " + "0x" + bits.ToString("X2") + " = 0x" + (b ^ bits)); // 0111

// Affiche:
// 0x04 ^ 0x03 = 0x07

Vérifier l'état d'un groupe de bits (AND)

C'est malheureusement très verbeux...

byte b= 0x07; // 0111
byte bits = 0x04; // 0100
if ((b & bits) == bits)
    Console.WriteLine("0x" + b.ToString("X2") + " contient 0x" + bits.ToString("X2"));

// Affiche:
// 0x07 contient 0x04.

Voir aussi :
http://www.codeproject.com/KB/cs/leftrightshift.aspx
(un bon tutoriel sur chaque opérateur sur bits en C#).