Attributes

S

switch

I've seen code where people pass in 'attributes' by using the | operator.
Like MULTI | TRANSPARENT | EDITABLE

I want to use this kind of thing in my own code, and I know you need to set
up each constant to be 1,2,4,8,16, etc, but my question is, given a value,
how do I test if an attribute is set ?
 
J

Jacob

switch said:
I've seen code where people pass in 'attributes' by using the | operator.
Like MULTI | TRANSPARENT | EDITABLE

I want to use this kind of thing in my own code, and I know you need to set
up each constant to be 1,2,4,8,16, etc, but my question is, given a value,
how do I test if an attribute is set ?

Use the binary and operator:

if (attribute & TRANSPARENT)
// TRANSPARENT is set
etc.
 
S

switch

Like this:
int attributes = getAttributesFromAMagicalPlace();
if ((attributes & MULTI) != 0) {
doMultiStuff();
}
if ((attributes & TRANSPARENT) != 0) {
doTransparentStuff();
}
if ((attributes & EDITABLE) != 0) {
doEditableStuff();
}

Thank you Sir.
 
J

Joona I Palaste

switch said:
Thank you Sir.

I am pleased you figured out my real gender so quickly. Most people who
don't know me initially assume I'm a woman (which I'm not, despite my
feminine-sounding name).

--
/-- Joona Palaste ([email protected]) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"We sorcerers don't like to eat our words, so to say."
- Sparrowhawk
 
R

Roedy Green

if (attribute & TRANSPARENT)

In forth that would be :
attribute TRANSPARENT AND IF

in C that would be :
if (attribute & TRANSPARENT)

but in Java it has to be :
if ( (attribute & TRANSPARENT) != 0 )
 
R

Roedy Green

Then it'd have to be

if ( (attribute & TRANSPARENT) == TRANSPARENT )

I did some work JavaDocing and cleaning a large Java project. The
thing I found more difficult to deal with than anything else was
deciding which enumeration masks were ints, which where single bit
mask and which where multiple bit masks and checking they were all
being used consistently.

Pascal with its sets and automatic enum numbering kept track. It
seems odd that Java can't do at least as well. The typical Pascal
implementation puts a fixed size or a cap on set size, which would
unlikely be considered acceptable in Java.

If we are not going to give any language support for bit map enums,
perhaps Sun could at least offer some naming conventions to help
clarify intentions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top