Register & Bitwise Operator

Numbering System

Bit Pattern

Bitwise Operators

AND Operation

Example:-

uint8_t sample=0x04; // Binary 0b0000 0100

sample &=8; // The value will be zero

OR Operation

Example:-

uint8_t sample=0x04; // Binary 0b0000 0100

sample |=8; // The value will be 12

Ex-OR Operation

Example:-

uint8_t sample=0x04; // Binary 0b0000 0100

sample ^=12; // The value will be 8

NOT Operator

It reverses all the bits 

    

Example:-

uint8_t sample=~4; // The value should be 251             

i.e. 0000 0100 ~ = 1111 1011 = 251

Rules :- The bit patterns should be represent as

                 1 byte= 8 bit = 2 nibble

                 1 nibble = 4 bit

So each byte can be represented as upper nibble and lower nibble.

      >> and << operators :-
 In general from      Value >> num

Here, num specifies the number of position to right shift the Value in value. Example :-

uint8_t a=32; // Binary representation 0b0010 0000            

a=a>>2;

In general from  Value << num

Here, num specifies the number of position to left shift the Value in value. Example :-

uint8_t a=1; // Binary representation 0b0000 0001

a<<=3;

Now execute the following instruction and find what happen

          uint8_t sample=4;

          sample | =(1<<3);

Thus the particular bit is set and it put on effect on other bits. So that the formula to set a particular bit without effecting other bits is-

          variable_name |=(1<<Bit_position);

Similarly to set multiple bit at the same time

          variable_name |=(1<<Bit_position1)| (1<<Bit_position2)| (1<<Bit_positionN);

To clear a particular bit

          variable_name &=~(1<<Bit_position);

Exapmle:-

                    uint8_t sample=0b00011111;

                    sample &=~(1<<3);

Similarly to clear multiple bit at a time

  variable_name &=~((1<<Bit_position1)| (1<<Bit_position2)| (1<<Bit_positionN));

To toggle a particular bit ^ is used

In general from  variable_name ^=(1<<Bit_position);

Exapmle:-

                    uint8_t sample=4;

                    sample ^=(1<<3);

                    sample ^=(1<<3);

variable_name ^=(1<<Bit_position);
Register Assign:

In all our discussion we learn how to set and clear a particular bit in byte. Let look at the following example –

PORTB|=(1<<PORTB7)|(1<<PORTB6); // Set PORTB7 & PORTB6
PORTB&=~((1<<PORTB5)|(1<<PORTB4)); // Clear PORTB7 & PORTB6

Here the Register is PORTB and in this register we can set and clear any bit at any time.