3

C++ で循環ビットシフトを実装しようとしています。ある時点を除いて、私はたくさんのゼロを取得します。

for (int n=0;n<12;n++) {
    unsigned char x=0x0f;
    x=((x<<n)|(x>>(8-n))); //chars are 8 bits
    cout<<hex<<"0x"<<(int)x<<endl;
}

私の出力は次のとおりです。

0xf
0x1e
0x3c
0x78
0xf0
0xe1
0xc3
0x87
0xf
0x0
0x0
0x0

ご覧のとおり、予想される 0x1e、0x3c などではなく、0x0 を取得し始めます。

for ループを 60 回程度反復するように拡張すると、数値が正しく返されます (多数のゼロの後)。

char には大きなスペースがあり、未使用のデータの「ギャップ」はゼロであると想定しています。私の理解は少し限られているので、何か提案をいただければ幸いです。これらのゼロを捨てる方法はありますか?

4

2 に答える 2

9

Shifting by a negative amount is undefined behavior.

You loop from 0 to 12, but you have an 8 - n in your shifts. So that will go negative.

If you want to handle n > 8, you'll need to take a modulus by 8. (assuming you want 8-bit circular shift.)


for (int n=0; n < 12; n++) {
    unsigned char x = 0x0f;
    int shift = n % 8;   //  Wrap modulus
    x = ((x << shift) | (x >> (8 - shift))); //chars are 8 bits
    cout << hex << "0x" << (int)x << endl;
}
于 2012-10-15T01:49:11.233 に答える
1

バイトを 7 を超えて左にシフトすると、結果は常に 0 になります。また、負の量だけシフトすることは定義されていません。

これを修正するには、シフトを型のサイズに制限する必要があります。

基本的:

unsigned char x = 0xf;
int shift = n&7;
x=((x<<shift)|(x>>(8-shift)))
于 2012-10-15T01:52:46.407 に答える