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....
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);
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With