Csharp/CSharp Tutorial/Data Type/Bitwise NOT

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

bitwise NOT for hexadecimal

<source lang="csharp">class MainClass {

 public static void Main()
 {
   byte byte1 = 0x9a;  // binary 10011010, decimal 154
   byte byte2 = 0xdb;  // binary 11011011, decimal 219
   byte result;
   System.Console.WriteLine("byte1 = " + byte1);
   System.Console.WriteLine("byte2 = " + byte2);
   
   result = (byte) ~byte1;
   System.Console.WriteLine("~byte1 = " + result);
 }

}</source>

byte1 = 154
byte2 = 219
~byte1 = 101

The bitwise NOT

<source lang="csharp">using System; class Example {

 public static void Main() { 
   sbyte b = -34; 

   for(int t=128; t > 0; t = t/2) { 
     if((b & t) != 0) 
         Console.Write("1 ");  
     if((b & t) == 0) 
         Console.Write("0 ");  
   } 
   Console.WriteLine(); 

   // reverse all bits 
   b = (sbyte) ~b; 

   for(int t=128; t > 0; t = t/2) { 
     if((b & t) != 0) 
        Console.Write("1 ");  
     if((b & t) == 0) 
        Console.Write("0 ");  
   } 
 } 

}</source>

1 1 0 1 1 1 1 0
0 0 1 0 0 0 0 1