だから私はこの問題を解決しようとしています:
ランダムな 32 ビットの正の整数が与えられ、3、4、5 番目の位置のビットの値を 24、25、26 番目の位置のビットの値と交換する必要があります。
だから私はこの問題を解決しようとしています:
ランダムな 32 ビットの正の整数が与えられ、3、4、5 番目の位置のビットの値を 24、25、26 番目の位置のビットの値と交換する必要があります。
これが明示的な解決策を必要としない問題であると仮定すると、ここにヒントがあります: を使用して問題のビットをマスク&
し、シフトを実行してから、OR
bitwise を使用し|
ます。
マスクを使用してビット 3、4、および 5 を「切り取る」ことができ、0x00000034
マスクを使用してビット 24、25、および 26 を「切り取る」ことができ0x07000000
ます。
インスピレーションを得るために、ビット反転の問題に対するこの解決策を見てください。
編集:(「宿題ではない」コメントへの回答)これは宿題ではないため、より詳細な説明を次に示します。
unsigned int val = ... // your value
unsigned int bits_03_04_05 = val & 0x00000034;
unsigned int bits_24_25_26 = val & 0x07000000;
// Cut out "holes" at bits 3, 4, 5, 24, 25, and 26 of the original value
unsigned int res = val & ~(0x00000034 | 0x07000000);
// Put bits 3, 4, and 5 in place
res |= bits_03_04_05 << 21;
// Put bits 23, 24, and 25 in place
res |= bits_24_25_26 >> 21;
どうですか:
// snag the values from 3,4,5 (small) and 24,25,26 (large)
int small = value & (7 << 2), large = value & (7 << 23);
// remove the old values, and add in the new ones
value = (value ^ (small | large)) | (large >> 21) | (small << 21);
(ビット1をLSBとしてカウントします。ビット0がLSBであることを意味する場合は、数値を1で調整します)