chsalvia
asked on
Using bitwise operators to create boolean flags
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?
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?
ASKER
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes ;-)
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
#define ALPHA 0x00000001
#define NUMBER 0x00000002
---
Harish