问题
How would i go about accessing the individual bits inside a c++ type, char
or any c++ other type for example.
回答1:
If you want access bit N
:
Get: (INPUT >> N) & 1;
Set: INPUT |= 1 << N;
Unset: INPUT &= ~(1 << N);
Toggle: INPUT ^= 1 << N;
回答2:
You would use the binary operators |
(or), &
(and) and ^
(xor) to set them. To set the third bit of variable a
, you would type, for instance:
a = a | 0x4
// c++ 14
a = a | 0b0100
Note that 4’s binary representation is 0100
回答3:
That is very easy
Lets say you need to access individual bits of an integer
Create a mask like this
int mask =1;
now, anding your numberwith this mask gives the value set at the zeroth bit
in order to access the bit set at ith position (indexes start from zero) , just and with (mask<
来源:https://stackoverflow.com/questions/9531214/access-individual-bits-in-a-char-c