Here is an example of a C source code to deal with the GPIO at the odroid XU3 board. My question is what is the >> 2
intended for in the constructions like this one:
*(gpio + (0x0c24 >> 2)) |= (1 << 2);
gpio
is a uint32_t
pointer.
The address 0x24
is given on a byte wise basis.
When we add 1 to 32 bit pointer, the address jumps 4 locations. So, we have to add the address/4
to get to the correct position. (>>2
is hte same as dividing by 4)
It's because the variable is declared like so:
static volatile uint32_t *gpio;
So it's a pointer to 32-bit unsigned integers. This means that if we add 1
in the code to the pointer, the actual address referenced will be 4 bytes later than before. This is how pointer arithmetic works in C.
So, to use the byte offset 0xc24
from the base, that offset needs to be scaled down by four, which is what a shift right of two bits does.
It could just as well be written:
*(gpio + 0xc24 / 4) |= (1 << 2);
But often you see shifts used for powers of two. Modern compilers do this optimization easily, you won't see a division in the code for this (or even a shift, since the term can be computed compile-time).