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....
views:
191answers:
6
+2
A:
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.
Amir Afghani
2010-03-19 20:26:52
The bitwise operations are faster and probably the better answer. The above solution is probably simpler to read.
Amir Afghani
2010-03-19 20:30:51
+3
A:
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);
Jack
2010-03-19 20:27:54
A:
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;
}
Mark E
2010-03-19 20:29:19
@Jeff, sure, but as it stands this is a decent, correct and readable answer. Such pendantry shouldn't merit a downvote.
Mark E
2010-03-19 21:08:57
I Didnt down vote. Actually I up voted and submitted an unrolled version of yours. Ppl should explain down votes.
Jeff Meatball Yang
2010-03-20 02:01:49
A:
You'll have to do this with bitwise operations:
ie:
while (my_char > 0) {
if my_char & 1
char_vector.push 1 // if the right most bit is 1
else
char_vector.push 0 // right most bit must be 0 if we fell through to the else
my_char = my_char >> 1 // right shift one position
}
if you need to, you can pad the char_vector with the remaining 0s, after you right shift to zero.
Josiah Kiehl
2010-03-19 20:29:35
Forgive the c-like pseudocode. ;) Does it not make sense, or are you just mentioning that I didn't write syntactically correct code? (which of course, I didn't intend to)
Josiah Kiehl
2010-03-22 20:56:43
A:
char c = 'C';
Vector<Boolean> vector = new Vector<Boolean>(16);
for (int i = Character.SIZE-1; i >=0; --i) {
int num = c >> i;
boolean set = (num & 1) == 1;
vector.add(Boolean.valueOf(set));
}
Tom
2010-03-19 20:42:29
A:
Unrolled loop:
int[] bits = new int[8]
bits[0] = (c & 1) > 0 ? 1 : 0;
bits[1] = (c & 2) > 0 ? 1 : 0;
bits[2] = (c & 4) > 0 ? 1 : 0;
bits[3] = (c & 8) > 0 ? 1 : 0;
bits[4] = (c & 16) > 0 ? 1 : 0;
bits[5] = (c & 32) > 0 ? 1 : 0;
bits[6] = (c & 64) > 0 ? 1 : 0;
bits[7] = (c & 128) > 0 ? 1 : 0;
Jeff Meatball Yang
2010-03-19 20:49:20