Skip to content

Instantly share code, notes, and snippets.

@faithandbrave
Created November 26, 2020 08:12
Show Gist options
  • Save faithandbrave/d8b4098c592cf6c606624a2f2f790a45 to your computer and use it in GitHub Desktop.
Save faithandbrave/d8b4098c592cf6c606624a2f2f790a45 to your computer and use it in GitHub Desktop.

下位Nビットを落とす

#include <iostream>
#include <bitset>
#include <cstdint>

int main() {
  std::uint8_t a = 0b1111'1111;
  std::uint8_t drop_lsb_0bits = a & -1; // 変更なし
  std::uint8_t drop_lsb_1bits = a & -2; // 2の倍数にする
  std::uint8_t drop_lsb_2bits = a & -4; // 4の倍数にする

  std::cout << std::bitset<8>(drop_lsb_0bits) << std::endl;
  std::cout << std::bitset<8>(drop_lsb_1bits) << std::endl;
  std::cout << std::bitset<8>(drop_lsb_2bits) << std::endl;
}

出力:

11111111
11111110
11111100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment