system
October 7, 2010, 2:19pm
1
I currently have a matrix of bytes that are either 1 or 0. For arguments sake lets say its a 1x8 matrix of 1 and 0. i.e. [1,0,1,0,1,0,1,0]
I need to combine this all into either a binary set such as B10101010 or a byte 0-255.
What would be my best bet for doing this? I'm completely lost right now and google is not helping much.
system
October 7, 2010, 2:50pm
2
int myArray[8] = { 1,0,1,0,1,1,0,0};
unsigned char result = 0;
for (int = 0; i < 8; i++) {
result <<= 1;
if (myArray[i]) {
result |= 1;
}
}
Reverse the loop if you want to assemble the bits in the opposite direction.
If you're confused about all the <<= and |=, look up your bitwise operators in C. It's time for you to meet and greet them.
Korman
For bonus points, eliminate the 'if'
system
October 7, 2010, 2:55pm
4
No Groove, we want to educate, not confuse, don't we?
result = (result << 1) | (myArray[i] & 1);
That would be overdoing it. If one was nasty, it also could be done with rotate through carry operations or the bit set operations. Probably that would take least instructions.
Korman