Method to iterate over the bits in a byte sent over serial [closed]

In my current project which integrates Arduino/avr IC with Raspberry-Pi, and each communicating via serial, I'm looking to send a byte of data to the Arduino from the RPi, which then would be iterated over, bit by bit.

Each bit represents a setting. If a bit is 0, then the Arduino would turn that respective device off, if a bit is 1, then Arduino would turn that respective device on. For example, a byte such as: 01100110, would mean the Arduino would have to turn four devices off, and four devices on.

I'm looking for information on how to take a byte over serial, and iterate over that byte bit by bit, and have the Arduino make decisions based on the value of each bit.

Excuse my post for lacking much technical detail, I'm refraining from using terms that are still very vague to me.

Regards.

• your question is a C++ programming question ..... it is not related to the Arduino specifically Jan 29, 2019 at 6:41

In all the examples below, `value` is the value of the byte

LSB -> MSB - so 00001111 would turn ON the first 4 devices and turn OFF the last 4

``````for(int i = 0, mask = 1; i < 8; i++, mask = mask << 1)
{
if (value & mask)
{
// bit is on
}
else
{
// bit is off
}
}
``````

Alternatively, you can do the following, but `value` will be altered

``````for(int i = 0; i < 8; i++, value = value >> 1)
{
if (value & 1)
{
// bit is on
}
else
{
// bit is off
}
}
``````

Working the other way around in each byte:
MSB -> LSB - so 00001111 would turn OFF the first 4 devices and turn ON the last 4

``````for(int i = 0, mask = 128; i < 8; i++, mask = mask >> 1)
{
if (value & mask)
{
// bit "i" is on
}
else
{
// bit "i" is off
}
}
``````

Alternatively, you can do the following, but `value` will be altered

``````for(int i = 0; i < 8; i++, value = value << 1)
{
if (value & 128)
{
// bit is on
}
else
{
// bit is off
}
}
``````