私の入力がある:中位のビットがパターンに一致する次の整数。
- ビット幅
n
のmask
をマスクし、いくつかはk
一部に1Sと> = 0 - ビットパターン
pattern
(必ずしも全てではない)のビットマスクが有する位置をオフセット1s。 - 私は
result
ような次の最大の整数を見つけたいval
整数:例えば
result > val
result & mask == pattern
、mask = 0xFF00
とpattern = 0x0100
を想定。その後、我々は次のような結果を期待する:
NextLargest(mask, pattern, 0x00000) => 0x00100
NextLargest(mask, pattern, 0x000FF) => 0x00100
NextLargest(mask, pattern, 0x010FE) => 0x001FF
NextLargest(mask, pattern, 0x010FF) => 0x10100
別の例は、 - mask = 0xF
とpattern = 0xF
を言います。その後、我々は期待:
NextLargest(mask, pattern, 0x20) => 0x2F.
私は「それをインクリメントについてmask
心配、ビット、または背面pattern
内を取り除くと返す」のようなものを試してみたが、私はエッジケースを打っておきます。問題は、ある整数の次に大きい倍数を見つける一般化のようなものです。ここで
#include <iostream>
using namespace std;
using uint32 = unsigned long;
uint32 NextLargest(int width, int offset, uint32 mask, uint32 pattern, uint32 val) {
unsigned long long ret = (val + 1) & ~mask;
if ((ret & ((1 << (offset + 1)) - 1)) == 0) {
// "carry" across the mask
ret += 1 << (offset + width);
}
return ret | pattern;
}
int main() {
// your code goes here
int width = 12;
int offset = 4;
uint32 significant_bits = (1 << (width + 1) - 1) << offset;
uint32 wanted_bits = 0xFFF << offset;
cout << hex;
// want 0xFFF1 -- correct
cout << NextLargest(width, offset, significant_bits, wanted_bits, 0) << endl;
// want 0xFFF2 -- correct
cout << NextLargest(width, offset, significant_bits, wanted_bits, 1) << endl;
// want 0x1FFFF0 -- incorrect, get 0xFFF0
cout << NextLargest(width, offset, significant_bits, wanted_bits, 0xF) << endl;
return 0;
}
それは同様pattern' 'と等しくなるように'ヴァル&mask'ための本当ですか? –
@RonおそらくこれはC++で行われているためですか?これは関連性があります。なぜなら、異なる言語がほとんど同じであっても、異なるビット操作関数を提供したり、有用なライブラリ関数などがある可能性があるからです。なぜ*それは関係ないでしょうか? –
'NextLargest(マスク、パターン、0x010FF)=> 0x101FF'は' => 0x10100'ではありませんか? – user2079303