0

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);
Serge Roussak
  • 1,731
  • 1
  • 14
  • 28

2 Answers2

1
  • 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)

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
1

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).

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Thank you. I loosed sight of the `uint32_t` in the `gpio`'s declaration. By the way: may I use the `uint8_t` here? I am newbie for ARM. As far as I know at the ARM addressing of the words is more optimal. – Serge Roussak Nov 01 '16 at 09:28