jewee
asked on
Validating bits
I have a char (1 byte) value inside a struct. I need to check each bit - and if certain bits are set, perform certain operations.
How do i check each bit within a byte?
How do i check each bit within a byte?
What language?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Sorry, I meant to post this under the C programming language.
Should work for C as well.
I would suggest you define the meanings for your bits (hex is often easiest):
#define VALID_USER 0x01
#define LOGGED_IN 0x02
#define HAS_DOG 0x04
#define FAST_CAR 0x08
#define GOLD_CARD 0x10
You could then define a specific combination of bits you want to test for with the "or" operater:
#define VALID_LOG_CAR (VALID_USER | LOGGED_IN | GLAD_CARD)
Then, loop the bytes you want to check, and test each byte with the "and" operater:
if ((c & VALID_LOG_CAR) == VALID_LOG_CAR)
{
}
Hope this helps.
James
#define VALID_USER 0x01
#define LOGGED_IN 0x02
#define HAS_DOG 0x04
#define FAST_CAR 0x08
#define GOLD_CARD 0x10
You could then define a specific combination of bits you want to test for with the "or" operater:
#define VALID_LOG_CAR (VALID_USER | LOGGED_IN | GLAD_CARD)
Then, loop the bytes you want to check, and test each byte with the "and" operater:
if ((c & VALID_LOG_CAR) == VALID_LOG_CAR)
{
}
Hope this helps.
James
ASKER
I am looking to validate each one individually - for example, if bit 7 is set, then perform some operation, if bit 6, then call another function...etc.
ASKER
I am reading from a binary file
Jewee that is what my example does, take a look. You get the byte and then you can view each individual bit to see
if it is set or not. If it is 0 it is not set, if it is not 0 then it is set. The value that you retrieve will be the value of that
bits placeholder. The bits run 0-7 for the byte, so you check each like so:
(MyByte & (1 << 0)) //Check bit 0
(MyByte & (1 << 0)) //Check bit 1
(MyByte & (1 << 0)) //Check bit 2
(MyByte & (1 << 0)) //Check bit 3
(MyByte & (1 << 0)) //Check bit 4
(MyByte & (1 << 0)) //Check bit 5
(MyByte & (1 << 0)) //Check bit 6
(MyByte & (1 << 0)) //Check bit 7
if it is set or not. If it is 0 it is not set, if it is not 0 then it is set. The value that you retrieve will be the value of that
bits placeholder. The bits run 0-7 for the byte, so you check each like so:
(MyByte & (1 << 0)) //Check bit 0
(MyByte & (1 << 0)) //Check bit 1
(MyByte & (1 << 0)) //Check bit 2
(MyByte & (1 << 0)) //Check bit 3
(MyByte & (1 << 0)) //Check bit 4
(MyByte & (1 << 0)) //Check bit 5
(MyByte & (1 << 0)) //Check bit 6
(MyByte & (1 << 0)) //Check bit 7