Different I/O pins of same PORT of ATMEGA8 not providing exact output
The expression 

PORTD &amp;= ~ 1 &lt;&lt; 4;


is actually interpreted as

PORTD &amp;= ((~1) &lt;&lt; 4);


due to operator precedence. In C++, the unary ~ operator is higher priority than binary &lt;&lt; operator. See https://en.cppreference.com/w/cpp/language/operator_precedence

Fix this by using parenthesis to enclose the 1 &lt;&lt; 4 expression:

PORTD &amp;= ~(1 &lt;&lt; 4);