How would i go about accessing the individual bits inside a c++ type, char
or any c++ other type for example.
To read a bit at a specific position, you must mask out all other bits in the value. The operator that assists in that process is the bitwise & (and). After you mask out all the other bits, the value that remains is either zero or some other value.
For accessing a specific bit, you can use Shift Operators . If it is always a 1 that you are going to reset, then you could use an & operation. But, if it can also take 0 value, then & operation will fail as 0 & 1 = 0 . You could use | (OR) during that time.
The smallest group of bits the language allows use to work with is the unsigned char , which is a group of 8 bits.
printf("int has %ud bits\n", sizeof(int) * 8); sizeof() returns the size in bytes of an integer, and then you multiply that result by 8 (bits per byte in 99.999% of cases)to get the size in bits of your integer, and therefore the size of the masks you have to apply.
If you want access bit N
:
Get: (INPUT >> N) & 1;
Set: INPUT |= 1 << N;
Unset: INPUT &= ~(1 << N);
Toggle: INPUT ^= 1 << N;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With