Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Advanced
Jan 18, 2005

Accessing Individual Bits of a Value

Ever needed to access individual bits of a value? It can be done with bitshifting and a sequence of logical &s quickly and easily. When finished, you will have a series of bit values that are only one bit in length.

//bit accesstest - using char as the source type
struct ByteBits
{
  unsigned bit0 : 1;
  unsigned bit1 : 1;
  unsigned bit2 : 1;
  unsigned bit3 : 1;
  unsigned bit4 : 1;
  unsigned bit5 : 1;
  unsigned bit6 : 1;
  unsigned bit7 : 1;
};

int main()
{
  ByteBits bittest;
  char value=170; //10101010 l-to-r in binary
  memcpy(&bittest,&value,1);

  //bittest.bit0->7 will be
  //0,1,0,1,0,1,0,1 respectively (the bits will be reversed
  //as that's how they are ordered in memory.
)
Zoltan Andras
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date