使用32位值进行64位旋转的有效方法

我需要使用2个32位寄存器旋转64位值。 有没有人遇到过这样做的有效方法?

好吧,正常旋转可以像这样实现:

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

所以,这里是对使用32位变量的64位实现的猜测:

 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; } 

基本上,我只是从高位字中取出旋转位,然后用低位字对它们进行OR运算,反之亦然。

这是一个快速测试:

 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\n", 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\n", hi, lo); } } 

这是一个替代实现,当n> = 32时交换值。它还处理n = 0或n = 32时的情况,这导致hi >> (32 - n)移位多于类型宽度,导致未定义的行为。

 void rot64 (uint32_t hi, uint32_t lo, uint32_t n, uint32_t *hi_out, uint32_t *lo_out) { /* Rotations go modulo 64 */ n &= 0x3f; /* Swap values if 32 <= n < 64 */ if (n & 0x20) { lo ^= hi; hi ^= lo; lo ^= hi; } /* Shift 0-31 steps */ uint8_t shift = n & 0x1f; if (!shift) { *hi_out = hi; *lo_out = lo; return; } *hi_out = (hi << shift) | (lo >> (32 - shift)); *lo_out = (lo << shift) | (hi >> (32 - shift)); }