2015-12-28 35 views
1

比方說,我有以下字節:特定字節設置4位

char* frame = new char[6]; 

這將導致這樣的:

00000000 00000000 00000000 00000000 00000000 00000000 

現在我拿的第一個字節,frame[0]並設置其最後4位這樣的:

frame[0] |= 1 << 7 
frame[0] |= 1 << 6 
frame[0] |= 1 << 5 
frame[0] |= 1 << 4 

第一字節現在:

11110000 

我在寫一個函數,它的編號介於0x00xF之間。該數字應寫入字節的前4位。

例如:功能已經完成

void setByte(char value) 
{ 
    // ... ?? 
} 

setByte(0xD) // 0xD = 00001101; 

後的字節現在這個樣子:

11111101 

我不知道我怎麼能做到這一點 - 也許這是可能的「將最後4位複製到另一個字節中?

回答

1

設置nibble的訣竅是首先清除所需的四位,然後清除新值中的OR。

使用0xF0掩碼來清除低位半字節;對於高半字節,掩碼是0x0F

char setLowerNibble(char orig, char nibble) { 
    char res = orig; 
    res &= 0xF0; // Clear out the lower nibble 
    res |= (nibble & 0x0F); // OR in the desired mask 
    return res; 
} 

char setUpperNibble(char orig, char nibble) { 
    char res = orig; 
    res &= 0x0F; // Clear out the upper nibble 
    res |= ((nibble << 4) & 0xF0); // OR in the desired mask 
    return res; 
} 

可以按如下方式使用它:

frame[0] = setLowerNibble(frame[0], lowerNibbleOfFrame0); 
frame[0] = setUpperNibble(frame[0], upperNibbleOfFrame0);