0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

bit演算の総まとめ[例題付き]

Last updated at Posted at 2025-04-27

基本のbit演算まとめ

演算 記号 説明
AND(論理積) & 両方1なら1、それ以外は0 1101 & 1011 = 1001
OR(論理和) | どっちか1なら1 1101 | 1101=1101
XOR(排他的論理和) ^ 違ってたら1、同じなら0 1101 ^ 1011 = 0110
NOT(否定) ~ 0と1を反転する ~1101 = 0010
左シフト << 左にビットをずらす(×2) 0011 << 1 = 0110
右シフト >> 右にビットをずらす(÷2) 0110 >> 1 = 0011

詳細

① AND(&)

cpp
int a = 5; // 5 = 0101
int b = 3; // 3 = 0011
cout << (a & b) << endl; // 出力:1(= 0001)

② OR(|)

cpp
int a = 5; // 0101
int b = 3; // 0011

cout << (a | b) << endl; // 出力:7(= 0111)

③ XOR(^)

cpp
int a = 5; // 0101
int b = 3; // 0011

cout << (a ^ b) << endl; // 出力:6(= 0110)

④ NOT(~)

cpp
int a = 5; // 0101

cout << (~a) << endl; // 出力:-6(コンピュータの内部表現の都合で負の数になる)

⑤ 左シフト(<<)

cpp
int a = 3; // 0011

cout << (a << 1) << endl; // 出力:6(= 0110)
cout << (a << 2) << endl; // 出力:12(= 1100)

a << 1 → 2倍

a << 2 → 4倍

a << 3 → 8倍
みたいにどんどん大きくなる!

⑥ 右シフト(>>)

cpp
int a = 12; // 1100

cout << (a >> 1) << endl; // 出力:6(= 0110)
cout << (a >> 2) << endl; // 出力:3(= 0011)

a >> 1 → 2で割った値

a >> 2 → 4で割った値

補足

書き方 意味
a << K aを左にKビットシフトするだけ(a自体は変わらない)
a <<= K aを左にKビットシフトして、その結果をaに代入する(aが変わる!)

bit演算に関するAtCoderのリンク一覧

2^N

Maximum Sum

Base 2

Binary Representation

CTZ

1-2-4 Test

Bitwise Exclusive

Bit Operation Ⅰ

Bit Operation Ⅱ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?