Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 274
  • Last Modified:

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?  
0
jewee
Asked:
jewee
1 Solution
 
giltjrCommented:
What language?
0
 
List244Commented:
C++:

#include <iostream>

using namespace std;

int main()
{
      char T ='D';
      for (int i=0;i<8;i++)
            cout << (T & (1 << i)) << ' ';
      return 0;
}

This shows you how you can use the bit operator to get the bit value from each.  You will see from that
example that it outputs:

0,0,4,0,0,0,64,0  Which tells you off/on for each if it is not 0.  The value is the value that bit represents.
0
 
jeweeAuthor Commented:
Sorry, I meant to post this under the C programming language.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
List244Commented:
Should work for C as well.
0
 
lostcarparkCommented:
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
0
 
jeweeAuthor Commented:
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.

0
 
jeweeAuthor Commented:
I am reading from a binary file
0
 
List244Commented:
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
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now