Search code examples
cembeddedbit-manipulationbitwise-operatorsbit-shift

Checking register value is setting the bit using C function


I have a snippet of code below that checks whether a register value is set.

# define My_register_array(index)    (*((P2VAR(uint32, AUTOMATIC, APPL_VAR))Group_register(index)))    /*eg: Group_register(0) address is 0xF3456775*/

# define SET_INIT(index)             ((uint32)1u << (index))

#define MY_CODE


FUNC(boolean, MY_CODE) bo_checkInit(uint32 index)
{
  boolean retVal = FALSE;

  /* Check register is initialized */
  if((My_register_array(index) & SET_INIT(index)) == SET_INIT(index))
  {
    retVal = TRUE;
  }

  return retVal;
}

int main()
{
   boolean retVal = FALSE;
   retVal = bo_checkInit(0); // call function 
   if(retVal)
   {
      printf("register is initialized\n");
   }
   else
   {
     printf("register is not initialized\n");
   }
   
   return 0;
} 

I am trying to understand this code and would like to know its purpose.

if((My_register_array(index) & SET_INIT(index)) == SET_INIT(index))

Is this code checking if the register value is set to 1? If anyone can explain this, it would help me understand the concept.


Solution

  • The result of & (binary AND) is a 1-bit wherever the bit is set in both operands, a zero-bit otherwise.

    So (X & BitMask) == BitMask becomes true only if all bits (only one in your case) in the mask are also set in X.