473,405 Members | 2,287 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,405 software developers and data experts.

Masks: Why?

I have often times seen masks used in C source code. I really don't
understand the purpose or functionality of this. I have seen used:

#define MASK 0x77

....

if(hello & MASK)

Also I don't (yes still don't) understand the purpose of the bitwise
operators. I understand there are times when you may pass to a
function:

func(ONE | TWO | THREE);

To pass those three options. What I don't understand is what that
means, what it is doing, and how the function knows that you passed
ONE, TWO, and THREE and not some value just equal to ONE | TWO | THREE
and another thing is what if ONE | THREE == TWO | FOUR. What then?
Mainly I just don't understand WHY a mask would be used, or why a
bitiwise operator would be used. I'm pretty sure I understand what a
bitwise operator does I just don't know why you would EVER need that
done. Thanks in advanced to anyone who helps someone who is thoroughly
confused.
Nori

Jun 5 '06 #1
10 2163

no*********@gmail.com wrote:
I have often times seen masks used in C source code. I really don't
understand the purpose or functionality of this. I have seen used:

#define MASK 0x77

...

if(hello & MASK)

Also I don't (yes still don't) understand the purpose of the bitwise
operators. I understand there are times when you may pass to a
function:

func(ONE | TWO | THREE);

To pass those three options. What I don't understand is what that
means, what it is doing, and how the function knows that you passed
ONE, TWO, and THREE and not some value just equal to ONE | TWO | THREE
and another thing is what if ONE | THREE == TWO | FOUR. What then?
Mainly I just don't understand WHY a mask would be used, or why a
bitiwise operator would be used. I'm pretty sure I understand what a
bitwise operator does I just don't know why you would EVER need that
done. Thanks in advanced to anyone who helps someone who is thoroughly
confused.


I'd still say you don't have a good grasp on bit representation of
values. I suggest you go back to some textbooks covering that.

Bitwise operators, and masks, are used to get/set/test individual bits
in a multi-bit value. Most often, these bits represent various flags
(e.g., if bit 5 is set, your MP3 player will be in repeat mode). Other
times, several values are packed into the same multi-bit field. A good
example is storage format of floating point numbers. Quite often (and I
am probably oversimplifying), they will be packed into a field not
unlike this: 1 bit for the sign of the mantissa, N bits for the value
of the mantissa, 1 bit for the sign of the exponent, M bits for the
value of the exponent.

Hope this clarifies things a bit.

Jun 5 '06 #2
no*********@gmail.com wrote:
I have often times seen masks used in C source code. I really don't
understand the purpose or functionality of this. I have seen used:

#define MASK 0x77

...

if(hello & MASK)

Also I don't (yes still don't) understand the purpose of the bitwise
operators.
To read or write a bit or groups of bits in a value without the other
bits being interfered with or interfering, and to do so efficiently.

It lets you represent (small) sets of values with machine integers.
I understand there are times when you may pass to a
function:

func(ONE | TWO | THREE);

To pass those three options. What I don't understand is what that
means,
If func expects a set of options, and ONE, TWO, and THREE are values
that represent (independant) sets of options (typically a single one
each), then the call says to take the /union/ of those sets -- ie all
the values -- and pass that to func.
what it is doing, and how the function knows that you passed
ONE, TWO, and THREE and not some value just equal to ONE | TWO | THREE
It doesn't, and it doesn't matter either.
and another thing is what if ONE | THREE == TWO | FOUR. What then?
Then the designer may be berated for a silly choice of values. Or
not, if it doesn't matter.
Mainly I just don't understand WHY a mask would be used, or why a
bitiwise operator would be used. I'm pretty sure I understand what a
bitwise operator does I just don't know why you would EVER need that
done.


Think of the value as a bunch of bits (which, by coincidence, is what
they are in most machines), each with its own specific meaning. Let's
say

enum { READ = 0x1, WRITE = 0x2, EXECUTE = 0x4 };

If bit 0 is set, we mean "allow reads" (of something, say files in a filing
system, or pages in a memory map), if bit 1 is set we mean "allow writes",
and if bit 2 is set we mean "allow execution".

If you want to test the read bit:

if (value & READ) readBitSet(); else readBitUnset();

The masking means that you /don't care/ about the WRITE and EXECUTE bits.

Similarly

value = value | WRITE; /* or value |= WRITE */

will switch on the WRITE bit (or leave it set, if it were set already)
/without changing/ the READ and EXECUTE bits. And

value = value & ~EXECUTE; /* or value &= ~EXECUTE */

will switch /off/ the EXECUTE bit (or leave it off, if it were off
already) without touching the others.

There are generalisations for when the values aren't just single bits.
For example, if you want to describe a node in a syntax tree, you
might use a single byte with five bits for its type and three for
its length [1] and then

thatByte & 0x7

will get you the length field (assuming you stored it at the low end)
and

thatByte & 0xf8

will get you the type field - which you may or may not want to shift
down.

[1] Of course you need to cope with long nodes somehow, eg by chaining.

--
Chris "seeker" Dollin
"Who are you? What do you want?" /Babylon 5/

Jun 5 '06 #3
On 2006-06-05 14:36, no*********@gmail.com wrote:
I have often times seen masks used in C source code. I really don't
understand the purpose or functionality of this. I have seen used:

#define MASK 0x77

...

if(hello & MASK)
This is used to pass only a "part" of hello, more specific all bits of
hello that are set that are also set in MASK.
Also I don't (yes still don't) understand the purpose of the bitwise
operators. I understand there are times when you may pass to a
function:

func(ONE | TWO | THREE);

To pass those three options. What I don't understand is what that
means, what it is doing, and how the function knows that you passed
ONE, TWO, and THREE and not some value just equal to ONE | TWO | THREE
It does not know this, the result is that it's one value that is passed,
and this value is the result of the |-operation applied to ONE, TWO and
THREE. Someplace in func there will be code like:

if (arg & ONE)
{
/* do something */
}

That will perform some operation if ONE was passed.
and another thing is what if ONE | THREE == TWO | FOUR. What then?
Trouble, the idea is that each of these masks will be different from the
others. Normally there will only be one bit set for each mask. For
example ONE might have the first bit set and all other unset, TWO have
the second set and all other unset and so on.
Mainly I just don't understand WHY a mask would be used, or why a
bitiwise operator would be used. I'm pretty sure I understand what a
bitwise operator does I just don't know why you would EVER need that
done.


Remember that one of the reasons that C was invented was to write an OS
in it, an OS have to deal with manipulating hardware and hardware often
use status-registers that have to be read or written. And these
registers generally use individual bits to signal status.

In many situations there is no reason to play around with individual
bits, using a a couple of normal int and setting them to 1 or 0 works
just as well and you get the benefit of naming each variable. However
for other uses such as some binary formats (compression comes to mind)
you have to be able to modify individual bits.

Erik Wikström
--
"I have always wished for my computer to be as easy to use as my
telephone; my wish has come true because I can no longer figure
out how to use my telephone" -- Bjarne Stroustrup
Jun 5 '06 #4

<no*********@gmail.com> wrote in message
news:11*********************@j55g2000cwa.googlegro ups.com...
I have often times seen masks used in C source code. I really don't
understand the purpose or functionality of this. I have seen used:

#define MASK 0x77

...

if(hello & MASK)

Also I don't (yes still don't) understand the purpose of the bitwise
operators. I understand there are times when you may pass to a
function:

func(ONE | TWO | THREE);

To pass those three options. What I don't understand is what that
means, what it is doing, and how the function knows that you passed
ONE, TWO, and THREE and not some value just equal to ONE | TWO | THREE
and another thing is what if ONE | THREE == TWO | FOUR. What then?
That means that whoever designed the values did a poor job.
Mask values can be defined in many ways, but should always be
such that only one bit is set. So:
#define ONE 1
#define TWO 2
#define THREE 4
#define FOUR 8

Anopther way:
#define ONE 1
#define TWO (1<<1)
#define THREE (1<<2)
etc.

Then ytou can use one parameter to specify that several options are
to be used. For example,
x = ONE | THREE | SEVEN
could be used to say that options 1, 3, and 7 should be performed:

if ( x & ONE ) {
/* perform otpion 1 */
}
if ( x & TWO ) {
/* perform option 2 */
}
etc.
Mainly I just don't understand WHY a mask would be used, or why a
bitiwise operator would be used. I'm pretty sure I understand what a
bitwise operator does I just don't know why you would EVER need that
done. Thanks in advanced to anyone who helps someone who is thoroughly
confused.
Nori

--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
Jun 5 '06 #5
"Fred Kleinschmidt" <fr******************@boeing.com> writes:
<no*********@gmail.com> wrote in message
news:11*********************@j55g2000cwa.googlegro ups.com...
I have often times seen masks used in C source code. I really don't
understand the purpose or functionality of this. I have seen used:

#define MASK 0x77

...

if(hello & MASK)

Also I don't (yes still don't) understand the purpose of the bitwise
operators. I understand there are times when you may pass to a
function:

func(ONE | TWO | THREE);

To pass those three options. What I don't understand is what that
means, what it is doing, and how the function knows that you passed
ONE, TWO, and THREE and not some value just equal to ONE | TWO | THREE
and another thing is what if ONE | THREE == TWO | FOUR. What then?


That means that whoever designed the values did a poor job.
Mask values can be defined in many ways, but should always be
such that only one bit is set. So:
#define ONE 1
#define TWO 2
#define THREE 4
#define FOUR 8

Actually it is quite common to have "masks" defined with *groups* of
bits being set. For example an 8 bit hardware register might be layed
out as

aaabbbcc

Where aaa and bbb are 3 bit integers, and cc is 2 bits, representing
some hardware setting. Say aaa=speed_1, bbb=speed_2,
cc=direction.

Then you might do

unsigned char* reg = (unsigned char*) REGISTER_ADDRESS;
unsigned speed_1, speed_2, dir;

...

assert(speed_1<8 && speed_2<8 && dir<4);
reg = speed_1<<5 | speed_2<<2 | dir;

To adjust a single item, say speed_1, you then need a bitmask with
several bits set:
reg = reg & ~(7<<5) | speed1<<5;

The same applies to bitmasks being used to pack values into an integer
e.g. to save storage space, or to implement a binary protocol.
--

John Devereux
Jun 5 '06 #6
Chris Dollin <ch**********@hp.com> wrote:
no*********@gmail.com wrote:
I have often times seen masks used in C source code. I really don't
understand the purpose or functionality of this. I have seen used:

#define MASK 0x77
...
if(hello & MASK)

Also I don't (yes still don't) understand the purpose of the bitwise
operators.
To read or write a bit or groups of bits in a value without the other
bits being interfered with or interfering, and to do so efficiently.

....
Mainly I just don't understand WHY a mask would be used, or why a
bitiwise operator would be used. I'm pretty sure I understand what a
bitwise operator does I just don't know why you would EVER need that
done.


Think of the value as a bunch of bits (which, by coincidence, is what
they are in most machines), each with its own specific meaning. Let's
say

enum { READ = 0x1, WRITE = 0x2, EXECUTE = 0x4 };

If bit 0 is set, we mean "allow reads" (of something, say files in a filing
system, or pages in a memory map), if bit 1 is set we mean "allow writes",
and if bit 2 is set we mean "allow execution".

If you want to test the read bit:

if (value & READ) readBitSet(); else readBitUnset();

The masking means that you /don't care/ about the WRITE and EXECUTE bits.

Similarly

value = value | WRITE; /* or value |= WRITE */

will switch on the WRITE bit (or leave it set, if it were set already)
/without changing/ the READ and EXECUTE bits. And

value = value & ~EXECUTE; /* or value &= ~EXECUTE */

will switch /off/ the EXECUTE bit (or leave it off, if it were off
already) without touching the others.

There are generalisations for when the values aren't just single bits.
For example, if you want to describe a node in a syntax tree, you
might use a single byte with five bits for its type and three for
its length [1] and then

thatByte & 0x7

will get you the length field (assuming you stored it at the low end)
and

thatByte & 0xf8

will get you the type field - which you may or may not want to shift
down.


You will find bit masks very frequently in embedded code, were
individual bits in peripheral registers or output ports control
hardware functions.

As an exercise, think how you could solve the following:

Write a program to control the traffic lights at a street
intersection. Use the following definitions:
( Many,many necessary details omitted ... )
/* Input/Output port controlling the lights */
volatile unsigned char * const LIGHT_CTRL =
(volatile unsigned char * const) 0xABCD;

/* Individual light definitions */
#define NS_RED 0x01U /* North-South red lights */
#define NS_YELLOW 0x02U /* North-South yellow lights */
#define NS_GREEN 0x04U /* North-South green lights */
#define EW_RED 0x08U /* East-West red lights */
#define EW_YELLOW 0x10U /* East-West yellow lights */
#define EW_GREEN 0x20U /* East-West green lights */
#define NS_BUTTON 0x40U /* North-South pedestrian request button */
#define EW_BUTTON 0x80U /* East-West pedestrian request button */
void light_on(unsigned char const light)
{
*LIGHT_CTRL |= light;
}

void light_off(unsigned char const light)
{
*LIGHT_CTRL &= ~light;
}

unsigned int pedestrian_request(unsigned char const button)
{
return !!(*LIGHT_CTRL & button);
}

void go_north_south()
{
light_off(NS_RED | NS_YELLOW | EW_GREEN | EW_YELLOW);
light_on (NS_GREEN | EW_RED);
}
....


[1] Of course you need to cope with long nodes somehow, eg by chaining.

Jun 5 '06 #7
As a realistic example where masks would be not just useful but
essential is a chess programme which uses bitboards to represent
the chess board. Crafty comes to mind.

Jun 5 '06 #8
On 2006-06-05, sp****@gmail.com <sp****@gmail.com> wrote:
As a realistic example where masks would be not just useful but
essential is a chess programme which uses bitboards to represent
the chess board. Crafty comes to mind.


Not sure if you've been told this before, but could you
be so nice as to quote something from
the posts you are replying to?
Although your post makes it as an interesting idea by itself
I think it's a followup to some other post, though.

Thank you.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Jun 6 '06 #9

Nelu wrote:
On 2006-06-05, sp****@gmail.com <sp****@gmail.com> wrote:
As a realistic example where masks would be not just useful but
essential is a chess programme which uses bitboards to represent
the chess board. Crafty comes to mind.


Not sure if you've been told this before, but could you
be so nice as to quote something from
the posts you are replying to?
Although your post makes it as an interesting idea by itself
I think it's a followup to some other post, though.

Thank you.


I wasn't replying to any specific post ; I was simply addressing the
general
topic of the thread. Is there any appropriate quoting to be made in
such a
case ?

Spiros Bousbouras

Jun 11 '06 #10
sp****@gmail.com wrote:

Nelu wrote:
On 2006-06-05, sp****@gmail.com <sp****@gmail.com> wrote:
> As a realistic example where masks would be not just useful but
> essential is a chess programme which uses bitboards to represent
> the chess board. Crafty comes to mind.


Not sure if you've been told this before, but could you
be so nice as to quote something from
the posts you are replying to?
Although your post makes it as an interesting idea by itself
I think it's a followup to some other post, though.

Thank you.


I wasn't replying to any specific post ; I was simply addressing the
general
topic of the thread. Is there any appropriate quoting to be made in
such a
case ?

Then "Although your post makes it as an interesting idea by itself"
probably applies. But you could have quoted the question from
the OP, nonetheless. Not all the time, the subject matches the
content. Sometimes the OP sets a subject that has nothing in common
with the question. If you quote the question is much clearer that
you are talking about the same thing as the OP.

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)
Jun 11 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Gianni Mariani | last post by:
Below is an example of how to do static type-checking of an erroneous set of input masks. The drawback is that it's a little too verbose and non-trivial to understand and to make it truly I'd...
2
by: Mark Lees | last post by:
I want to create an input mask for a phone number and I would like the area code to always be (801). However, I want the users to be able to edit it if necessary. Would it look like this =...
4
by: David W. Fenton | last post by:
I'm working on a subform where users put in 24-hour time. On their paper forms, they've been accustomed to referring to midnight as 24:00 (instead of as 0:00, which kind of makes sense from a human...
6
by: Regnab | last post by:
Morning All, I'm trying to ensure that when the user enters a number on a form, the database automatically leaves a space after the 3rd number. I've tried to do this using input masks, but when...
2
by: bobrics | last post by:
Hi, I am trying to understand what is wrong with my code. What I have below is a part of a linear feedback shift register. But it's simplified to the point where it does not matter. The main...
4
by: Dave | last post by:
Hello - Say I have a 32 bit value in data (v:4, r:4, l:8, p:16) unsigned char data; Now, for portabilities sake, I want to use shifts and masks to access these fields, instead of accessing...
3
by: Dave | last post by:
I need to rewrite the following using shifts and masks for portability sakes, and to get rid of the BYTE_ORDER issue. /* CODE */ struct test { #if BYTE_ORDER == BIG_ENDIAN unsigned char ...
12
by: panjap | last post by:
a few days a go i was kindly helped with the trouble i was having on editing lables wjhere i wanted to change access' messages to my own. Below si the qeustion i set a few days agoa , which worked...
0
by: =?Utf-8?B?RGV2ZXJz?= | last post by:
I'm trying to display formatted numeric values with various masks, such as ##,###,##0.0000, but I'm having a terrible time with the MaskedTextBox control. Even though I've bound it to a numeric...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.