2010-12-14 19 views

回答

11

您可以按位將所有這些位設置爲0,並將4位設置爲0,將所有其他位設置爲1(這是將4位設置爲1的補數)。然後你可以像平常一樣按位或按位。

val &= ~0xf; // Clear lower 4 bits. Note: ~0xf == 0xfffffff0 
val |= lower4Bits & 0xf; // Worth anding with the 4 bits set to 1 to make sure no 
          // other bits are set. 
33

一般:

value = (value & ~mask) | (newvalue & mask); 

mask是所有位的值被改變(其中只有)設置爲1 - 它會在你的情況下0xf。 newvalue是一個包含這些位的新狀態的值 - 所有其他位基本上被忽略。

這適用於支持按位運算符的所有類型。

+0

你能舉一個具體的例子嗎?假設我有:n = 1024.我想要將位從位置3更改爲7(包括從最低有效位0開始)到k = 19。結果應該是:1176.我該如何實現它?謝謝。 – dh16 2017-06-23 21:41:39

0

使用按位運算符或|當你想一個字節的位從0更改爲1

使用位運算符和&當你想從1字節的位更改爲0

#include <stdio.h> 

int byte; 
int chb; 

int main() { 
// Change bit 2 of byte from 0 to 1 
byte = 0b10101010;  
chb = 0b00000100;  //0 to 1 changer byte 
printf("%d\n",byte); // display current status of byte 

byte = byte | chb;  // perform 0 to 1 single bit changing operation 
printf("%d\n",byte); 

// Change bit 2 of byte back from 1 to 0 
chb = 0b11111011;  //1 to 0 changer byte 

byte = byte & chb;  // perform 1 to 0 single bit changing operation 
printf("%d\n",byte); 
} 

也許有更好的方法,我不知道。這會幫你現在。

相關問題