Replace digitalWrite with a selective bitwise operation I have the following code with digitalWrite I aim to write with bitwise operation only.
No portability concerns here whatsoever. (for atmega328p here)

#define DATAOUT 11//MOSI 
byte commandbits = B11000000;
for (int i = 7; i &gt;= 3; i--) {
    digitalWrite(DATAOUT, commandbits &amp; (1 &lt;&lt; i));
}


I came up with something like this below which works.

#define DATAOUT 11//MOSI 
byte commandbits = B11000000;
for (int i = 7; i &gt;= 3; i--) {
    PORTB = (PORTB &amp;(~(1&lt;&lt;3))) | (((commandbits &amp;(1 &lt;&lt; i))&gt;&gt;i) &lt;&lt; 3);
}


Is this the most concise way. Is there a way to simplify it?
Personally I'd expand it out a little:

if (commandbits &amp; (1 &lt;&lt; i)) {
    PORTB |= (1&lt;&lt;3);
} else {
    PORTB &amp;= ~(1&lt;&lt;3);
}


It's far more readable, and there are less shifts to mess around with. Plus the AVR has bit set and bit clear operations which that will make use of, especially since it's now using literal values. You could actually replace those values with literals:

if (commandbits &amp; (1 &lt;&lt; i)) {
    PORTB |= 0x08;
} else {
    PORTB &amp;= 0xF7;
}