Skip to main content
Associate III
July 1, 2024
Question

bit shift >> and & operation

  • July 1, 2024
  • 2 replies
  • 997 views

Hi i m coding function to write 8 bit data to a slave device, what does the (byte & 0x01) do in the for loop and what does the shift right statement ( byte = byte >> 1;) do ? 

void write8bit(uint8_t byte)
{
	int i;
	for (i = 0; i<8; i++)
	{
		lowClk();
		if (byte & 0x01) 
		{
			Data_HI();
		}
		else
		{
			Data_Lo();
		}
		Delay(3);
		byte = byte >> 1;
		HiClk();
		Delay(3);
	}
}
This topic has been closed for replies.

2 replies

Tesla DeLorean
Guru
July 1, 2024

It's implementing a LSB (least significant bit) first method, the & 1 check bit zero, the shift >>1 rotates the byte so the next check of bit 0 will have the subsequent bit

ie

Bit 0

Bit 1

Bit 2

Bit 3

..

Bit 7

Tips, Buy me a coffee, or three.. PayPal Venmo (See Profile) Up vote any posts that you find helpful, it shows what's working..
Peter BENSCH
ST Technical Moderator
July 1, 2024

To put it precisely: >>1 does not rotate, but shifts. 

Beginners like @StanCosgrove should understand the difference:

  • when rotating, a bit that falls out of the byte/word is inserted at the other end
  • when shifting, such a bit is discarded

Regards
/Peter

In order to give better visibility on the answered topics, please click on Accept as Solution on the reply which solved your issue or answered your question.