我有一個功能來切換每個十六進制數字的第0位和第3位,但它使用26操作。我只是想把它減少到1到25個操作。只能使用按位操作! 〜&^| + < < >>。減少操作次數
int swap30(int x) {
int m = 0b10001000 << 24;
int m1 = 0b10001000 << 16;
int m2 = 0b10001000 << 8;
int m3 = 0b10001000;
int mask1 = m | m1 | m2 | m3;
int z = 0b01100110 << 24;
int z1 = 0b01100110 << 16;
int z2 = 0b01100110 << 8;
int z3 = 0b01100110;
int mask2 = z | z1 | z2 | z3;
int y = 0b00010001 << 24;
int y1 = 0b00010001 << 16;
int y2 = 0b00010001 << 8;
int y3 = 0b00010001;
int mask3 = y | y1 | y2 | y3;
int three = x & mask1;
int stable = x & mask2;
int one = x & mask3;
int final2 = ((three >> 3) & mask3) | stable | (one << 3);
return final2;
}
這應該寧可在[http://codereview.stackexchange.com/](http://codereview.stackexchange.com/) – AntonH
編譯器將可能預計算'mask1','mask2'和'mask3',所以你不會在運行時產生這些命中。 –
這個問題似乎是題外話題,因爲它屬於Code Review。 –