Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating bits of a char

Assuming I have char "C" whose ascii code is 0110 0111. How can I iterate over its bits? I would like to build a vector from these 1's and 0's....

like image 258
Hamza Yerlikaya Avatar asked Mar 19 '10 20:03

Hamza Yerlikaya


3 Answers

You can easily iterate over them using bitwise operators:

char c = 'C';
for (int i = 0; i < 8; ++i)
{
  // extract the i-th bit
  int b = ((c & 1<<i) >> i);
  // b will be 1 if i-th bit is set, 0 otherwise

  // do whatever you want with b
}

you can optimize it (as suggested in comments):

int b = ((c >> i) & 1);
like image 67
Jack Avatar answered Nov 01 '22 10:11

Jack


A character has an integer value. Something like this will work :

 int myChar = 42;
 String binstr = Integer.toBinaryString(myChar);

The rest I'll leave to you as an exercise - but all you have to do now is iterate over the String representation of your binary value and do whatever it was that you planned on doing.

like image 41
Amir Afghani Avatar answered Nov 01 '22 10:11

Amir Afghani


Just use bitwise checks at each position you care about. Something like the following will create an array bits that holds the individual values.

char c = 'C';
int[] bits = new int[8];

int j = 0;
for(int i = 1; i <= 256; i *= 2){
    bits[j++] = (c & i) > 0 ? 1 : 0;
}
like image 2
Mark Elliot Avatar answered Nov 01 '22 12:11

Mark Elliot