Hi,
In bit manipulations using bitwise operators, what is a mask and why is it needed?
thnx
Hi,
In bit manipulations using bitwise operators, what is a mask and why is it needed?
thnx
say you have a program that if the user whats a particular option on
you could use a boolean variable for this or you ould use "bit flags"
where ase each bit of say an int represents a flag
bit 0 is one thing on or off
bit 1 is something else
if you wanted to test this values you would "Mask" out the other bts in the int like so
[Code]
#include <stdio.h>
#define OPTION 0x01
int main(void)
{
char ch = 0;
int flags = 0;
printf("Hit a Key To Toggle the Bit Flag On Hit 'o' to turn it off\n");
if((ch = getchar()) != 'o')
flags |= OPTION; // set the first bit or our option flag on
else
flags &= ^OPTION; // set the Option flag off
if(flags & OPTION)
printf("The Option is Enabled!");
return 0;
}
forgot to end my code tag.
Code:#include <stdio.h> #define OPTION 0x01 int main(void) { char ch = 0; int flags = 0; printf("Hit a Key To Toggle the Bit Flag On Hit 'o' to turn it off\n"); if((ch = getchar()) != 'o') flags |= OPTION; // set the first bit or our option flag on else flags &= ^OPTION; // set the Option flag off if(flags & OPTION) printf("The Option is Enabled!"); return 0; }
keep getting loged out...
So if i am thinking correct, the mask can be anything to use in different situations, but it's used usually with AND right?
thnx
yup.
ADVISORY: This users posts are rated CP-MA, for Mature Audiences only.
>So if i am thinking correct, the mask can be anything to use in
>different situations, but it's used usually with AND right?
The reason why an AND is used is that
0 AND 0 = 0
0 AND 1 = 0
1 AND 0 = 0
1 AND 1 = 1
So if you have the byte
1101:0110
And you want to test if bit 3 is set (i.e. is equal to 1), then you can define the mask
0000:1000
And then AND the mask with the byte, which results in
0000:0000
So bit 3 is not set.
Code:byte = 0xD6; mask = 0x08; if ((byte & mask) > 0) /* bit 3 is set */
it's useful for saving space. 1 char = 8 bits.
i think OR can be used to set bits. set a mask, like
i've only seen xor used in encripting. i remember something called eqv(in basic i think), but i've forgotten what it was. can someone remind me?Code:0010 0001, OR 0100 0011 and you get 0110 0011.
Use XOR if you want to switch bits (1->0, 0->1)
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
0100:1101 XOR 0000:1111 would produce 0100:0010
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.