2014-01-15 56 views
1

我以下輸入:位操作者

int category; 
int ID 

ID是以這種方式形成一個數字:

//  CCXXXXNN 
ID = 0x12345678; 

而類別爲0x0到0xFF之間的數字。

我想檢查類別是否等於ID的CC部分。我該怎麼做?如果有必要,我可以將類別從int更改爲uint。

回答

3

您可以左移你有類別值到適當的位置,並在ID只是那些位與相應的一些比較:

ID & 0xff000000 == category << 24 // Mask off the high bits of ID, compare with category shifted into those bits 

,或者你可以右鍵 - 移動ID的類別位並對照類別值進行測試:

(ID >> 24) & 0xff == category // Put the high bits of ID in the low bits of an int, and mask off that. 

個人而言,我會爲零件編寫存取器函數並使用它們,因爲它使事情更具可讀性和靈活性,並且更容易出錯。
根據我的經驗,錯誤很容易發生,很難找到。

int get_category(int id) { return (id >> 24) & 0xff; } 
int get_xxxx(int id)  { return (id >> 16) & 0xffff; } 
int get_nn(int id)  { return id & 0xff; } 

if (get_category(ID) == category && get_nn(ID) < 57) 
    // and so on 
2

ID & 0xff000000 == category << 24

+0

非常感謝! – Jepessen

+0

是不是應該24而不是6? – adrin

+0

是的,我編輯了它 –

1
(ID & 0xff000000) == (category << (6 * 4)) 
1

實現它與工會的另一種方式:

int category = 12; 

union u 
{ 
    int ID; 
    struct a 
    { 
     BYTE dummy[3]; 
     BYTE category; 
    } b; 
} ; 

u temp; 

if (temp.b.category == category) 
{ 
    // ... 
}