Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Is it possible to access each bit in a byte using C++. For example if i have

char * a = NULL;
a = new char[500];


or

char a[500];


Like how one accesses each individual element using its index , is there any similar method to access each bit in C++.

Please mention a method if feasible in C++ and also the difference between accessing those bits in the pointer method and in the normal array initialization method.

Is it possible to realise a linear string in 2 dimensional matrix form using these combination of bits.
Posted
Comments
Graham Breach 13-May-13 6:02am    
This smells like homework.

1 solution

Suppose, for generality:

C++
const int  N = 500;
a = new char[N];
char b[N];


You access bit bitno of either a or b in the same way (note: not tested):

C++
int getbit(int bitno, int x[], int size)
{
  if ( bitno < 0 || bitno >= (size*8) )
  {
    // throw an exception here
  }
  int byte, b;
  byte = bitno / 8;
  b = bitno % 8
  return (x[byte] >> b) & 0x01;
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 5-Jun-13 23:12pm    
Looks right; even if something a bit off, it's easy to fix by thinking just a bit. My 101. :-)
—SA
CPallini 6-Jun-13 1:49am    
:-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900