Convert int[] to byte

Hi there!

I'm stuck here with the following problem:

I've got an int array which stores eight numbers (0s and 1s). I'd like to convert this array into a single byte.

like this:

int data[] = {0, 1, 1, 0, 0, 1, 1, 1} -> byte data = 0x67 (or: byte data = B01100111)

Now, I know that this conversion requires an own function, but as I'm totally new to bits and bytes, I really can't figure out how such a function should look like.

Maybe someone could help me out, or if you're to busy, give me a site, where I could learn it myself...

First off, you can save a little space in your program by using

char data = {0, 1, 1, 0, 0, 1, 1, 1};

To convert it to a single byte, you can do:

char i;
char result = 0;
for (i = 0; i < 8; i++)
if (data*)*

  • result |= 1 << (7 - i);*
    - Ben

First off, you can save a little space in your program by using

char data = {0, 1, 1, 0, 0, 1, 1, 1};

Depends on where the data is loaded from, but I suggest to even use :

bool data[] = {0, 1, 1, 0, 0, 1, 1, 1};

It will take 16 times less space than int, and 8 times less than byte… (Ok this is theory, in fact very few compilers really store bools on a single bit… But I think that it’s safer to use bool when you mean bool, just to remember what your code means ^^ )

(btw, afaik the C++ legal keyword is “bool” … Does anyone knows why Arduino uses “boolean” ? Staying close from Processing maybe ?)

Wow, that was fast! Thank's a lot, I'll try it out tomorrow. ;)