We help IT Professionals succeed at work.

# Using bitwise operators to create boolean flags

on
Medium Priority
312 Views
I recently learned how to use bitwise operators to create 8 boolean flags using a single variable.  The purpose was to create a character map where I could define customized qualities, similar to the built-in lib functions like isalpha, isdigit, etc.

But suppose I want to have 16 flags?  I tried using a short instead of a char so I get 2 bytes to work with, and thus 16 bits to use as boolean flags.

But, I must be doing something wrong because when I change use a short array rather than a char array, I get results which are off sometimes.

Here I have 10 customized flags:

#define ALPHA 0x0001
#define NUMBER 0x0002
#define UPPER 0x0004
#define LOWER 0x0008
#define PUNCT 0x0010
#define DELIM 0x0020
#define STOP 0x0040
#define SPACE 0x0080
#define CURRENCY 0x8000
#define ELEMENT 0x0103

Then, I go through the first 127 characters like:

unsigned short __charmap[] = {
DELIM | STOP,
DELIM | ELEMENT,

...etc.

Yet, it doesn't work properly.  Can anyone spot something I'm doing wrong?
Comment
Watch Question

## View Solutions Only

Engineer
CERTIFIED EXPERT

Commented:
Hi, try having 4 more zeroes at the beginning.. as in

#define ALPHA 0x00000001
#define NUMBER 0x00000002

---
Harish

Commented:
Nevermind -

I just had the hex values wrong.  It should be:

#define ALPHA 0x0001
#define NUMBER 0x0002
#define UPPER 0x0004
#define LOWER 0x0008
#define PUNCT 0x0010
#define DELIM 0x0020
#define STOP 0x0040
#define SPACE 0x0080
#define CURRENCY 0x0100
#define ELEMENT 0x0200

Commented:
The value 0x0103 that you use for ELEMENT has 3 bits set, the 0x0100, 0x0001 and 0x0002 bits. This means every ELEMENt would always have the ALPHA and NUMBER bit set as well.

You should better define the new values like this:
#define CURRENCY 0x0100
#define ELEMENT 0x0200

This way you are using seperate bits for each property.

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
Yes ;-)
Commented:

#define ALPHA 0x0001
#define NUMBER 0x0002
#define UPPER 0x0004
#define LOWER 0x0008
#define PUNCT 0x0010
#define DELIM 0x0020
#define STOP 0x0040
#define SPACE 0x0080
#define CURRENCY 0x8000
#define ELEMENT 0x0103

It also is a better idea to have this as
#define ALPHA (1 << 0)
#define NUMBER (1 << 1)
#define UPPER  (1  << 2)
...
#define  CURRENCY (1 << 15)
And in this case:
#define ELEMENT ((1 << 8) + 0x3)

If element contains only 1 bit, you see something is wrong....
When you start using 32 bit flags, it easier to see what your doing  -- a common programming mistake
is miscounting your places....with the shift syntax, you don't mistake (but you may miscompute!)

##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile