Electronic – PIC Assembler Bitwise Operator Left Shift

microcontrollerpic

I am following a tutorial on programming baseline 12F series PICs in assembler.

I have a question regarding bitwise operators specifically the << left shift operator.

Lets use an example the PIC I'm using is a 12F509 so if I wanted to set GP1 and GP0 as outputs and the rest of the I/O pins as inputs I would normally do it like this.

movlw    b'111100' ; Set GP1 and GP0 as outputs
tris     GPIO    

If I wanted to use a bitwise operator to achieve the same thing I think I could use << left shift like this.

movlw    0<<1 ; Shift 0 left once to set GP1 and GP0 as outputs
tris     GPIO

I take it after this operation the last 2 bits would be 00. Since << left shift shifts all the bits to the left discards the leftmost bit and sets the bit to the right to 0.

This is my understanding of how the bit shift left operator works. Hopefully it's correct.

Now in the tutorial this bit of code was introduced there was an explanation of what it does but not how it does it.

movlw    ~(1<<1) ; set GP1 as an output
tris     GPIO

I'm going to take a stab at what this code is doing let me know if I've got it right. It's first shifting a binary 1 left once into the GP1 position which leaves a 0 in the GP0 position.

So when the operation in the parenthesis is complete the value would look like this 000010.

Then the ~ is inverting the 1 in the GP1 position to 0 and the 0 in all of the other positions to 1? Leaving the value set to 111101 (GP1 as an output)?

Thanks In Advance.

Best Answer

The operand of the PIC instruction is evaluated to a constant at assembly time- the code emitted will contain a constant in that position. For example:

movlw ~(1<<1) ; set GP1 as an output

1 << 1 is evaluated as b'00000010' (b'00000001' left-shifted by 1 - it is understood that a 0 is shifted in)

The the complement is applied (all 8 bits are flipped), so you get

b'11111101'

and the code emitted is

movlw b'11111101'

It's the same as directly writing the above except you might find it more readable to write it in the way shown.