About extracting characters from and int, bitwise operators.

We went over bitwise operators very briefly in class, and it was mentioned that extract characters from an int using masks, but with what little we covered I still don't get this concept fully, or how it's done. I googled unpacking characters, read some of the search result which were all on packing, but I'm still a bit lost. Can someone trying and explain this?
I hope this explaination will help somewhat:

Sometimes the bits of an int are used to flag some states, e.g. if an item is available and such.
There are roughly two cases to handle:
* Extracting a single bit from a bit-field, and
* setting a single bit in a bit field,

Let's assume you have a char value as bit-field (char consists of 8 bits) and you want to know what the fifth bit of this field states.
Then you create a bit-mask which depresses all other bits then the fifth.
The mask for the fifth bit would look: 0b00010000
If you conjunct this mask via bitwise 'and' operator , you depress all other bits then the fifth.
The evaluation of this conjunction will ether be 0b00000000 if the fifth bit was zero, or 0b00010000 if the fifth bit was 1.
Here an example how to code such:
1
2
char bit_mask = 0b00010000;
bool is_fifth_bit_set = (bool)(my_bit_field & bit mask);

If you want to set a single bit in a bit field, you need to conjunct this bit via bitwise 'or'. Before doing that you have to place this bit at the correct place within the bit mask (via shift-operator).
Here an example how to set the fifth bit of the bit field.
1
2
3
4
bool my_flag;  // represents a single bit, whereby 'false' represents 0, and 'true' represents 1
...   // set  my_flag  to true or false
char bit_mask = (char)my_flag << 4;  // shifts the bit at the fifth place
my_bit_field = my_bit_field | bit mask;  // conjuncts the bit field via bitwise 'or' 

If it's still unclear how the bit mask work, I suggest that you comprehend some examples by yourself using paper and pen.
Last edited on
Yes, that did help. Thank you.
*corrected error*
I have recognized now that my explanation for setting a singe bit in a bit-field was wrong! We need different approches, depending on whether the flag is either false or true
Here the correct way, hopefully the right ;-)

* If the flag to set is false, our mask looks for the fiftth bit: 0b11101111. Conjunct this via bitwise 'and' to the bit field.

* If the flag to set is true, our mask looks for the fifth bit 0b00010000. Needs conjuncted via bitwise 'or' to the bit field.


Topic archived. No new replies allowed.