I want to build my own byte using 0's and 1's.
i.e., (pseudo code)
byte b = 0;
for (int x = 0; x < 8; x++) {
int i = getInteger(); //the integer will only ever be 0 or 1
b = b + i;
}
I don't know if that makes sense?
I don't want to add the integers together, I want to "join" them to make a byte
(like constructing a string).
Assuming you're building the byte msb (most significant bit) first, something like:
byte b = 0;
for (int x = 0; x < 8; x++)
{
b |= getInteger(); //OR in the bit at bit 0
b <<= 1; //shift one bit to the left
}//for
Do you understand bit-wise operations like AND, OR and shift?
Yes, or you can still use addition:
byte b = 0;
for (int x = 0; x < 8; x++) {
b = b + getInteger(); //the integer will only ever be 0 or 1
b << 1;
}
Also *2 as above, I posted before I saw that.
Or, along the same lines:
b = b + b + i;
dougp
6
There's also bitxxxxx at the reference page.
byte b = 0;
for (int x = 0; x < 8; x++) {
b = b + getInteger(); //the integer will only ever be 0 or 1
b = b << 1;
}
Wow, so many great answers!
Thanks to everyone for all your help.
I went with:
byte b = 0;
for (int x = 0; x < 8; x++) {
b |= getInteger() << x;
}
This LSB approach suited my application.
Of course, I could have used:
byte b = 0;
for (int x = 0; x < 8; x++) {
b |= getInteger() << (7 - x);
}
...for MSB.
Cheers
or, for MSB first:
byte b = 0;
for (int x = 7; x >= 0; x--) {
b |= getInteger() << x;
}