Let's say I read a certain bit in PIND and assign it to variable val
uint8_t val = (PIND & (1<<PD7));
Suppose I want to take the bit I just read and write it to PB5 (or to a dynamic bit in PORTB specified by a variable). One way to do it is:
if (val) PORTB |= 1<<PB5; else PORTB &= ~(1<<PB5);
I've tested it, and it works. There seems to be another way to do it:
PORTB = (PORTB & (~(1<<PB5))) | ((val>>PD7)<<PB5);
It works on paper, but something goes wrong when I actually run this code. I suspect I'm missing something trivial, but I just can't figure it out. So my question is twofold: what is wrong with this code, and whether it even makes sense to do it any other way than through the if statement.