Search code examples
cbit-manipulationbitavr

Rotate a bitmap represented by an array of bytes


In an AVR, I'm using an array of eight bytes to store a picture displayed on an 8x8 LED matrix. The picture needs to be rotated from time to time. So, given the picture defined as:

uint8_t rows[8] = {
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001,
    0b11111111
};

I want to "rotate" this anticlockwise to get as:

uint8_t rows2[8] = {
    0b11111111,
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001,
    0b00000001
};

Or this if done clockwise, :

uint8_t rows3[8] = {
    0b10000000,
    0b10000000,
    0b10000000,
    0b10000000,
    0b10000000,
    0b10000000,
    0b10000000,
    0b11111111
};

How do I do this in straight C?


Solution

  • Some bitwise operations can do the trick.

    #include <inttypes.h>
    
    int main(){
    
      uint8_t rows[8] = {
          0b11111111,
          0b00000001,
          0b00000001,
          0b00111111,
          0b00000001,
          0b00000001,
          0b00000001,
          0b11111111
      };
    
    
      uint8_t rows2[8] = {0, 0, 0, 0, 0, 0, 0, 0};
      uint8_t rows3[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    
      int i, j;
      // rotate clockwise
      for(i=0; i<8; ++i){
        for(j=0; j<8; ++j){
          rows3[i] = (  ( (rows[j] & (1 << (7-i) ) ) >> (7-i) ) << j ) | rows3[i];
        }
      }
    
      // rotate anti-clockwise
      for(i=0; i<8; ++i){
        for(j=0; j<8; ++j){
          rows2[i] = (  ( (rows[j] & (1 << i ) ) >> i ) << (7-j) ) | rows2[i];
        }
      }
    }
    

    In the clockwise case, you get each (7-i)-th bit of the j-th original byte with (rows[j] & (1 << (7-i) ) ) >> (7-i) and then shift it to the j-th position. You collect all the bits by doing an "or" (|) with the byte itself, so it is very important to initialize the array with 0s. The anti-clockwise case is analogous, changing the indexing. I used another letter to test it, that let you know for sure if the rotation is working properly. If you need further explanation, please just ask.

    If you want to look the result, I'm using the function in this SO question: Is there a printf converter to print in binary format?