日記帳

プログラミングのことをつぶやく日記です。

C++の2進数の左ビットシフト,右ビットシフトの挙動

C++の2進数の左ビットシフト,右ビットシフトの挙動を確認する機会があったのでメモする.

左ビットシフト

  cout << (1 << 0) << endl;
  cout << (1 << 1) << endl;
  cout << (1 << 2) << endl;
  cout << (1 << 3) << endl;
  cout << (1 << 4) << endl;
  cout << (1 << 5) << endl;
  cout << (1 << 6) << endl;
  cout << (1 << 7) << endl;
  cout << (1 << 8) << endl;

出力結果

1
2
4
8
16
32
64
128
256

2進数の1に対して2Kを掛けていることが分かる.

右ビットシフト

左ビットシフトと比べると,ちょっとルールが増えるので,MicrosoftのDocを参考にした.

learn.microsoft.com

  unsigned short short11 = 1024;
  bitset<16> bitset11{short11};
  cout << bitset11 << endl;  // 0b00000100'00000000

  unsigned short short12 = short11 >> 1;  // 512
  bitset<16> bitset12{short12};
  cout << bitset12 << endl;  // 0b00000010'00000000

  unsigned short short13 = short11 >> 10;  // 1
  bitset<16> bitset13{short13};
  cout << bitset13 << endl;  // 0b00000000'00000001

  unsigned short short14 = short11 >> 11;  // 0
  bitset<16> bitset14{short14};
  cout << bitset14 << endl;  // 0b00000000'00000000

出力結果

0000010000000000
0000001000000000
0000000000000001
0000000000000000

右ビットシフトは,2Kを割る処理であることが分かる.増えたルールとしては,左側の空きは0で埋める.右側にはみ出たビットは無視されることが分かる.shortは2バイトなので,16ビットである.