C 设置位后打印变量
我试图在8位变量中设置一位。 每次我在设置一个特定位后打印变量时,我总是得到值1C 设置位后打印变量,c,bit-manipulation,C,Bit Manipulation,我试图在8位变量中设置一位。 每次我在设置一个特定位后打印变量时,我总是得到值1 uint8 value; value = (1<<1 || value) printf(%x \n,value); //prints 1 instead of 2 value = (1<<2 || value) printf(%x \n,value); //prints 1 instead of 4 您正在使用布尔“或”| |。按位“或”是| 另外,您还没有初始化值,所以不能期望它是任何值
uint8 value;
value = (1<<1 || value)
printf(%x \n,value); //prints 1 instead of 2
value = (1<<2 || value)
printf(%x \n,value); //prints 1 instead of 4
您正在使用布尔“或”| |。按位“或”是|
另外,您还没有初始化值,所以不能期望它是任何值。不,您不会这样做 要设置一个位,请使用1 例如,要设置最低有效位,请使用1或 即: 要设置位1:
unsigned char val = 4;
// set bit 1
val |= 1 << 1;
printf("Value now: %x\n", val);
一个完整的例子
#include <stdio.h>
char* get_binary(unsigned char buffer, char* binary) {
for (int i = 0; i < 8; ++i) {
int bit = (buffer >> i) & 1;
binary[7 - i] = bit ? '1' : '0';
}
return binary;
}
int main() {
unsigned char val = 4; // val now 100
int bits_to_shift;
unsigned char buffer[10] = { 0 };
unsigned char* p = buffer;
// set bit 0
val |= 1;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now 5 :- 101
// To set bit 1 (ie set so we have 111), shift to position then OR
// set bit 1
bits_to_shift = 1;
val |= 1 << bits_to_shift;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now 7 :- 111
// set bit 3
bits_to_shift = 3;
val |= 1 << bits_to_shift;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now F :- 1111
}
您需要按位OR,而不是逻辑OR:| not | | |,因为| |被视为布尔值。任何_but _zero或任何_but _zero都是TRUE,TRUE是1。@user996142按位OR和逻辑OR都执行布尔或运算。。。不同之处在于它们对|单个位位置| |整个值执行的操作值也未初始化。@Dmitri:FYI,该标准区分按位和逻辑布尔运算符。
#include <stdio.h>
char* get_binary(unsigned char buffer, char* binary) {
for (int i = 0; i < 8; ++i) {
int bit = (buffer >> i) & 1;
binary[7 - i] = bit ? '1' : '0';
}
return binary;
}
int main() {
unsigned char val = 4; // val now 100
int bits_to_shift;
unsigned char buffer[10] = { 0 };
unsigned char* p = buffer;
// set bit 0
val |= 1;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now 5 :- 101
// To set bit 1 (ie set so we have 111), shift to position then OR
// set bit 1
bits_to_shift = 1;
val |= 1 << bits_to_shift;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now 7 :- 111
// set bit 3
bits_to_shift = 3;
val |= 1 << bits_to_shift;
printf("Value now: %x, binary=%s\n", val, get_binary(val, p)); // val now F :- 1111
}