# Convert bit ti byte

Hello I need to transfer an array containing 8 bits ( 10110100 for example bytes ) by inserting it in a single byte the value 180. The transferred data when it is received I have to convert it back into individual bits maybe within an Array.

Convert 10110100 —> 180

180 -> trasmission

180-> Convert 10110100

If you mean that the source array contains 8 bytes, each representing a bit then I suppose the first question I would have is why not hold those 8 bits in a single byte in the first place ?

1 Like

Please show us how this array was declared and written to

How this connected to the topic?

No one answered my question: how do I convert this

10110111 in this 180.

You still haven't answered the question of how the 0's and 1's are defined in your program. Can't really answer without knowing that.

As you wrote it there's no conversion necessary. The number is stored as the same 8bits whether you want it represented as decimal or binary or hex it doesn't matter.

Do you have an array of 8 byte variables? Or an array of int? Or are they characters that need to convert from ASCII?

Show some code and you'll get an answer.

How to insert 8 bits into one byte.

``````bool arr[] = { 0, 0, 1, 0, 1, 1, 0, 1};
uint8_t result;

for(uitn8_t cnt = 0; cnt < 8; cnt++){
SETBIT(cnt, arr[cnt]);
}
``````

For the reverse there is CHECKBIT(.....)

your code is wrong, test the SETBIT() macro

The loop below doesn't change the `result` byte at all

You don't need any conversion, because `0b10110100 = 180`.

I think that is a typo. It was probably supposed to have result as the address and not cnt. That way it works. The SETBIT macro is fine.

Even with this fix the result will be wrong because the `SETBIT()` can be only used for set bit to 1 and not to 0. It is not as @buckfast_beekeeper used it.

Correct code

``````bool arr[] = { 0, 0, 1, 0, 1, 1, 0, 1};
uint8_t result = 0;

for(uitn8_t cnt = 0; cnt < 8; cnt++){
if (arr[cnt])
SETBIT(result, cnt);
}
``````

Oh I see. Yes, he's doing it wrong. That code needs an extra if statement otherwise it sets all bits to 1.

1 Like

I basically have 8 on/off buttons. I need to transfer a byte data to another device where there are relays. Unfortunately I have so many groups of 8 buttons and I have to find a way to transfer this data with a few bytes.

The on/off 0/1 false/true data is on a bool variable. Or on a bool array.

Thanks so cnt is a Byte variable?

Still waiting.

you can use the code from the post #12 to convert a bool array to the byte

no, the byte to transfer will be in the `result` variable

I write the code when I know how to do it.

But if you're just reading switches then why have a bool array at all? Store 8 switch states in a byte and then you don't need to convert anything.

If you have them on the same port you can even read them all at once as a single byte.

There's probably a way better way to do what OP wants than this workaround. That's why the code would help.

1 Like