|Fundamental C - Basic Bits|
|Written by Harry Fairhead|
|Tuesday, 23 March 2021|
Page 2 of 2
Of course, in each case you don't have to use a variable to specify the mask you could just use a numeric literal.
For example instead of:
int flag = 0xFFFF; int result = flag ^ mask;
you can write:
int result = flag ^ 0xFFFF;
Also, if you want to update the flag rather than derive a new result, you can use:
to perform the update directly.
For example, instead of:
int flag = flag ^ 0xFFFF;
you can use:
int flag ^= 0xFFFF;
Bits in the mask that are 0 are unaffected by any of the operations.
What sorts of things do you use masking operations for?
Often a low-level API will require that particular bits in a status word are set or unset to make it operate in a particular way. Similarly, hardware registers are generally organized into groups of bits that you have to change to control the device.
A very common application is to extract the RGB color information from a single int representing the color of a pixel. For example:
int RGBcolor=0x010203; int B=RGBcolor & 0x0000FF; int G=RGBcolor & 0x00FF00; int R=RGBcolor & 0xFF0000;
takes an RGB value and splits it up into its components using appropriate masks. The result is that you end up with 0x010000 stored in R, 0x000200 in G and 0x000003 in B. Notice that the value of B is correct, but R and G are incorrect - the bits need shifting to the right. This brings us to the use of the shift operators.
Not in this extract:
Remote C/C++ Development With NetBeans
Getting Started With C/C++ On The Micro:bit
Fundamental C: Getting Closer To The Machine
Now available as a paperback and ebook from Amazon.
Also see the companion volume: Applying C
To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
or email your comment to: email@example.com
|Last Updated ( Tuesday, 23 March 2021 )|