Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
982 views
in Technique[技术] by (71.8m points)

c - Efficient way of doing 64 bit rotate using 32 bit values

I need to rotate a 64 bit value using 2 32 bit registers. Has anyone come across an efficient way of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, a normal rotate can be implemented like this:

unsigned int rotate(unsigned int bits, unsigned int n) {
    return bits << n | (bits >> (32 - n));
}

So, here's a guess at a 64-bit implementation with 32-bit vars:

void bit_rotate_left_64(unsigned int hi, unsigned int lo, unsigned int n,
                        unsigned int *out_hi, unsigned int *out_lo) {
    unsigned int hi_shift, hi_rotated;
    unsigned int lo_shift, lo_rotated;

    hi_shift = hi << n;
    hi_rotated = hi >> (32 - n);

    lo_shift = lo << n;
    lo_rotated = lo >> (32 - n);

    *out_hi = hi_shift | lo_rotated;
    *out_lo = lo_shift | hi_rotated;
}

Basically, I'm just taking the rotated bits from the high word and OR-ing them with the low word, and vice-versa.

Here's a quick test:

int main(int argc, char *argv[]) { 
    /* watch the one move left */
    hi = 0;
    lo = 1;
    for (i = 0; i < 129; i++) {
        bit_rotate_left_64(hi, lo, 1, &hi, &lo);
        printf("Result: %.8x %.8x
", hi, lo);
    }

    /* same as above, but the 0 moves left */
    hi = -1U;
    lo = 0xFFFFFFFF ^ 1;
    for (i = 0; i < 129; i++) {
        bit_rotate_left_64(hi, lo, 1, &hi, &lo);
        printf("Result: %.8x %.8x
", hi, lo);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...