问题
So I have a 16 bit number. Say that the variable name for it is Bits. I want to make it so that Bits[2:0] = 001, 100, and 000, without changing anything else. I'm not sure how to do it, because all I can think of is ORing the bit I want to be a 1 with 1, but I'm not sure how to clear the other bits so that they're 0. If anyone has advice, I'd appreciate it. Thanks!
回答1:
To clear certain bits, &
with the inverse of the bits to be cleared. Then you can |
in the bits you want.
In this case, you want to zero out the lower three bits (111
in binary or 7
in decimal), so we &
with ~7
to clear those bits.
Bits = (Bits & ~7) | 1; // set lower three bits of Bits to 001
回答2:
union
structures allow the ability to specify the number of bits a variable has and address each bit of a bigger variable individually.
union {
short value;
struct {
unsigned char bit0 : 1;
unsigned char bit1 : 1;
unsigned char bit2 : 1;
unsigned char bit3 : 1;
unsigned char bit4 : 1;
unsigned char bit5 : 1;
unsigned char bit6 : 1;
unsigned char bit7 : 1;
unsigned char bit8 : 1;
unsigned char bit9 : 1;
unsigned char bit10 : 1;
unsigned char bit11 : 1;
unsigned char bit12 : 1;
unsigned char bit13 : 1;
unsigned char bit14 : 1;
unsigned char bit15 : 1;
} bits;
} var;
Now you have a variable named var
that hold a 16-bit integer which can be referenced by var.value
, and you have access to each individual bit of this variable by acessing var.bits.bit0
through var.bits.bit15
.
By setting var.value = 0;
all bits are set to 0 too. By setting var.bits.bit0 = 1;
you automatically change the value of var.value
to 0x8000
, or as seen in binary, 1000000000000000
.
If you intention is change only the 3 last bits, you can simplify the structure to something more like this:
union {
short value;
struct {
unsigned short header : 13;
unsigned char bit13 : 1;
unsigned char bit14 : 1;
unsigned char bit15 : 1;
} bits;
} var;
Now you have the var.bits.header
, that is a 13-bits variable, and 3 other 1-bit variables you can play with.
But notice C++ does not support this kind of structure, so for best C to C++ portability you might prefer to use bitwise operations instead as proposed by @nneonneo.
来源:https://stackoverflow.com/questions/15915198/changing-bits-in-an-int-in-c