2009-09-22 37 views
1

我有一個應用程序,需要操縱nybbles,甚至可能在一次甚至個別位。 C#中有一個庫可以幫助我嗎?操縱Nybbles和更小的C#

+0

半字節是一個完全有效的拼寫,但我會刪除多餘的標籤。 – RCIX 2009-09-22 20:38:05

+1

每天學習新東西。但是,nybble與Color不相上下; D – user7116 2009-09-22 20:44:45

回答

5

您可以使用BitVector32來操作32位整數中的位,並使用BitArray來表示一組布爾變量。

而且,它很容易寫了幾個函數來處理各個位:

public bool GetBitValue(int integer, int bit) { 
    return (integer & (1 << bit)) != 0; 
} 

public bool SetBitValue(ref int integer, int bit, bool value) { 
    if (value) 
     integer |= 1 << bit; 
    else 
     integer &= ~(1 << bit); 
} 
+0

優雅的解決方案,我喜歡它! – ParmesanCodice 2009-09-22 20:43:36

2

庫實際上是不必要的

uint myVar = 257; 
const uint SOME_FLAG_A = 256 // 100000000 
const uint SOME_FLAG_B = 16 // 000010000 
const uint SOME_FLAG_C = 1 // 000000001 

if(myVar & SOME_FLAG_A == SOME_FLAG_A) 
    Console.WriteLine("Bit A is set!"); 
else 
    Console.WriteLine("Bit A is not set."); 

if(myVar & SOME_FLAG_B == SOME_FLAG_B) 
    Console.WriteLine("Bit B is set!"); 
else 
    Console.WriteLine("Bit B is not set."); 

myVar = myVar | SOME_FLAG_B; 

if(myVar & SOME_FLAG_B == SOME_FLAG_B) 
    Console.WriteLine("Bit B is set!"); 
else 
    Console.WriteLine("Bit B is not set."); 

if(myVar & SOME_FLAG_C == SOME_FLAG_C) 
    Console.WriteLine("Bit C is set!"); 
else 
    Console.WriteLine("Bit C is not set.");