473,394 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Need help understanding more about masking

31
how can i use bitwise masking in C++
please explain
Oct 27 '06 #1
1 3377
Banfa
9,065 Expert Mod 8TB
Sorry about the delay.

So when you declare a variable of integer type (char, short, int, long and their unsigned versions) then a lot of the time you use that variable to store a number using normal assignment and arithmetic operators.

However the variable is represented in memory by a fixed number of bits for any variable V this is equal to

sizeof v * CHAR_BIT

CHAR_BIT is defined in limits.h and is typically 8 but can have other values as it is platform dependent.

Typically the number of bits in various integer types are

char 8 bits
short 16 bits
int 16 or 32 bits
long 32 bits

More and more platforms also support a 64 bit integer type.

Bit masking occurs when you decided that rather than treat an integer variable as a value you will use it's individual bits to represent different values. You may want to do this to save memory or to mimic some hardware or for other reasons.

In order to access the individual bits of the variable then we have to use the bitwise operators as follows

& AND
| OR
^ XOR
~ NOT

to allow us to access the individual bits. When you use a bitwise operator the variables are acted on a bit at a time, that is in the expression

c = a & b;

bit 0 of c(the result) is the result of ANDing bit 0 and a and bit 0 of bit, the result does not effect any other bits in c. Put another way the bits are all handled in isolation from each other.

AND (&) is a binary operator and outputs 1 if both inputs are 1 otherwise it outputs 0.

OR (|) is a binary operator and outputs 1 if either input is 1 otherwise it outputs 0

XOR (^) is a binary operator and outputs 1 if either but not both inputs are 1 otherwise it outputs 0

NOT (~) is a unary operator, it inverts the bit value, i.e. outputs 1 if it was 0 and 0 if it was 1.

AND, OR, XOR and NOT are all associative.

Other useful operators when access bits are

>> shift left
<< shift right

Note that the implementation of the shift operators (particularly left shift) is platform dependent and can either be an arithmetic shift or a logical shift. For this reason among others it is best practice when using an integer variable by accessing it's bits directly to do so on an unsigned version of the type that you wish to use.

Onto an example, take this structure definition

Expand|Select|Wrap|Line Numbers
  1. #define HD_FLAG_TEA     0x01    // Note if the preference isn't tea then it's coffee
  2. #define HD_FLAG_MILK    0x02
  3. #define HD_FLAG_SUGER   0x04
  4. #define HD_FLAG_LEMON   0x08
  5.  
  6. typedef struct hot_drink_preference {
  7.     char          temperature;  // Prefered Drink Temerature in Celsius
  8.     unsigned char flags;        // Mask of bits containing other drink preferences
  9. } HDP;
  10.  
  11. HDP BanfaDP;
  12.  
  13. BanfaDP.temperature = 86;
  14. BanfaDP.flags = HD_FLAG_MILK;
  15.  
So the structure has 2 members, temperature representing the prefered temperature of the drink and flags which is a bit mask of other preferences.

Also note I have some #defines, these are the bits that I will be using in the flags member, look at the values they are defined to, note that they are equivilent to the binary values

0001
0010
0100
1000

There are no overlapping bits, and of course the is not 0 flag, these #defines do not represent the value that indicates if a particular preference is liked, the represent the bit position of the bit that indicates if a particular preference is liked.

So what operations would I like to do on my flags member, well common ones are

test a particular bit
set a particular bit
clear a particular bit

test a particular bit, return true or false. Not in bitwise operations (and in C in general) 0 is false any other value is true, if fact it might to better to expresses the 2 states as false and NOT false.

When I test a bit I am uninterested in the all the other bits, I want the result to have a 0 for all bits I am not interested in and the value of the bit I am interested in. Then if the bit of interest is 0 the result will be 0 (false) and if the bit of interest is 1 then result will be the value of that bit (NOT false). The AND operator does this

result = flags & bitOfInterest;

result will either have the value 0 or bitOfInterest after this statement

using the above example

Expand|Select|Wrap|Line Numbers
  1. if (BanfaDP.flags & HD_FLAG_SUGER)
  2. {
  3.     printf("Banfa takes suger\n");
  4. }
  5. else
  6. {
  7.     printf("Banfa doesn't take suger\n");
  8. }
  9.  
set a particular bit, setting a bit means giving it the value 1. So for any bit not of interest I want the result to have value of that original bit. For the bit of interest the result should have a value of 1 regardless of the original value. This is the OR operation because

x OR 0 = x
x OR 1 = 1

so

result = flags | bitOfInterest;

again as an example from above

Expand|Select|Wrap|Line Numbers
  1. // Set Suger as a drink perference for Banfa
  2. BanfaDP.flags |= HD_FLAG_SUGER;
  3.  
clear a particular bit, clearing a bit means giving it the value 0. Bits not of interest should have the same value in the result as they started, the bit of interest should end with a value of 0 regardless of what it's starting value is. So where OP stands for some undefined operation

x OP 0 = x <- Bits not of interest
x OP 1 = 0 <- Bit of interest

The answer may not be obvious because it requires 2 operations, first we have to invert the bitOfInterest value using NOT

x OP NOT(0) = x <- Bits not of interest
x OP NOT(1) = 0 <- Bit of interest

Giving

x OP 1 = x <- Bits not of interest
x OP 0 = 0 <- Bit of interest

You may recogniste this as AND so we have

result = flags & ~bitOfInterest;

from the example

Expand|Select|Wrap|Line Numbers
  1. // Clear Suger as a drink perference for Banfa
  2. BanfaDP.flags &= ~HD_FLAG_SUGER;
  3.  

Because of the associativeity of the bitwise operators you can set and clear more than 1 option at a time.

Expand|Select|Wrap|Line Numbers
  1. // Set Tea and Lemon as a drink perference for Banfa
  2. BanfaDP.flags |= HD_FLAG_TEA | HD_FLAG_LEMON;
  3.  
  4. // Clear Tea and Lemon as a drink perference for Banfa
  5. BanfaDP.flags &= ~(HD_FLAG_TEA | HD_FLAG_LEMON);
  6.  
  7. // Set drink preferences clearing all other options
  8. BanfaDP.flags = HD_FLAG_MILK;
  9.  
You can test multiple bits at the same time but it is not quite so straight forward

Expand|Select|Wrap|Line Numbers
  1. // OR
  2. if (BanfaDP.flags & (HD_FLAG_MILK | HD_FLAG_SUGER))
  3. {
  4.     // Banfa takes milk or suger
  5. }
  6.  
  7. // AND
  8. if (BanfaDP.flags & (HD_FLAG_MILK | HD_FLAG_SUGER) == (HD_FLAG_MILK | HD_FLAG_SUGER))
  9. {
  10.     // Banfa takes milk and suger
  11. }
  12.  

I suggest you try some of this out yourself in a test program.
Oct 31 '06 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Piotr | last post by:
Please help me, I can't solve this problem: I have domain: www.main_domain.com/index.php?userid=23&parametr1=2&parametr2=3 (and other site files like...
2
by: Ginchy | last post by:
I have uploaded a small 3 page web using MS Publisher 2003 and after uploading I switched on url masking to cloak the url. I am certain that it worked fine. I simply changed the colour scheme...
19
by: James Fortune | last post by:
I have a lot of respect for David Fenton and Allen Browne, but I don't understand why people who know how to write code to completely replace a front end do not write something that will automate...
1
by: john sutor | last post by:
Is there a way in C# to add masking (for a date format) to a textbox?
0
by: Dana Epp | last post by:
I have a ToolBarButton that when I set it to disabled (button.Enabled = false;) causes a really ugly gray masking effect to take place. This is normal and the intended way of the button, but I...
11
by: solandre | last post by:
my motivation is as follows: i have to binarysearch several million times an long that is several million items big. this costs time, although i use Array.Binarysearch<long>. so i try to keep...
2
by: Pete | last post by:
Hi, First, thanks for any time you spend helping me, I'm at a loss. I'm not bit-savvy, so I apologize if this is extremely simple, or I am going about this the wrong way. I am trying to take a...
0
by: =?Utf-8?B?TWFyayBDb2xsYXJk?= | last post by:
I'm using the MaskedTextBox to make sure the user inserts a valid international phone number. I want to set the Mask property so that the user sees +49-__-____-____ in the text box. I set the...
9
by: Daniel Smedegaard Buus | last post by:
Hey all :) I was wondering about the $error_types (I particularly notice the 's' suffix when reading the manual) parameter for 'set_error_handler()': Can be used to mask the triggering of the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.