Rotating a bitmap 90 degrees

前端 未结 9 1729
粉色の甜心
粉色の甜心 2021-02-04 05:49

I have a one 64-bit integer, which I need to rotate 90 degrees in 8 x 8 area (preferably with straight bit-manipulation). I cannot figure out any handy algorith

9条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 06:44

    To expand on my comment to Ira's answer, you can use:

    #define ROT_BIT_0(X)    X, (X)|0x1UL
    #define ROT_BIT_1(X)    ROT_BIT_0(X), ROT_BIT_0((X) | 0x100UL)
    #define ROT_BIT_2(X)    ROT_BIT_1(X), ROT_BIT_1((X) | 0x10000UL)
    #define ROT_BIT_3(X)    ROT_BIT_2(X), ROT_BIT_2((X) | 0x1000000UL)
    #define ROT_BIT_4(X)    ROT_BIT_3(X), ROT_BIT_3((X) | 0x100000000UL)
    #define ROT_BIT_5(X)    ROT_BIT_4(X), ROT_BIT_4((X) | 0x10000000000UL)
    #define ROT_BIT_6(X)    ROT_BIT_5(X), ROT_BIT_5((X) | 0x1000000000000UL)
    #define ROT_BIT_7(X)    ROT_BIT_6(X), ROT_BIT_6((X) | 0x100000000000000UL)
    
    static unsigned long rot90[256] = { ROT_BIT_7(0) };
    
    unsigned long rotate90(unsigned long v)
    {
        unsigned long r = 0;
        r |= rot90[(v>>56) & 0xff];
        r |= rot90[(v>>48) & 0xff] << 1;
        r |= rot90[(v>>40) & 0xff] << 2;
        r |= rot90[(v>>32) & 0xff] << 3;
        r |= rot90[(v>>24) & 0xff] << 4;
        r |= rot90[(v>>16) & 0xff] << 5;
        r |= rot90[(v>>8) & 0xff] << 6;
        r |= rot90[v & 0xff] << 7;
        return r;
    }
    

    This depends on 'unsigned long' being 64 bits, of course, and does the rotate assuming the bits are in row-major order with the msb being the upper right, which seems to be the case in this question....

提交回复
热议问题