 # AND Bitwise SPI question

Hi guys!,

trying to overcome this awkward n00b-phase, I have a question about some BITwise magic I came accros in a sketch which is used to read from an EEPROM through SPI bit banging. Here is the piece of code:

``````int read_8(int address)
{
char bit;
char inbit;
char index;
int value = 0;
chip_select_low();
for(index = 0; index < 8; index++)
{
inbit = bit & 0x01;
if(inbit == 1)
{
value = value + (0x80>>index);
sclk();
}
else
{
sclk();
}
}
chip_select_high();
return value;
}
``````

If I’m right this piece of code reads out a byte bit by bit starting with the MSB and ending with the LSB. I think I understand the code except this line:

``````inbit = bit & 0x01;
``````

Why is this line nessecary? Can’t the ‘bit’ variable not be used directly for the following if-statement?

I hope somebody can give me an explanation about this cheers!

Why is this line nessecary? Can't the 'bit' variable not be used directly for the following if-statement?

digitalRead will return either HIGH or LOW. HIGH is defined as 1 and LOW is defined as zero. The line "inbit = bit & 0x01;" will make certain that inbit is indeed 1 or 0. Since we know already however that bit is either 1 or 0, it really isn't needed and so you could use "bit" directly as you suggested.

Looks like it could be simplified even more as:

``````int read_8(int address)
{
int value         = 0;
unsigned int bit  = 0x80;

chip_select_low();

do
{
if ( digitalRead(From_Data_Out) & 0x01 )
{
value |= bit;
}

sclk();
} while ( bit >>= 1 )

chip_select_high();

return value;
}
``````