Bits, binary, and bitwise operators
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · このページには最新のブラウザ(SharedArrayBuffer対応)が必要です。Chrome、Edge、Firefox、Safariを最新バージョンに更新してください。
English
Numbers are bits
- Inside the computer, every
intis a row of bits — each bit is a0or a1. - We usually read numbers in base 10, but the machine stores them in base 2 (binary).
- Bitwise operators let you look at and change individual bits.
日本語
数字はビット
- コンピュータ内部では、すべての
intがビットの列である——各ビットは0か1である。 - 私たちは通常10進法で数を読むが、機械はそれらを2進法で格納する。
- ビット演算子により、個々のビットを参照したり変更したりできる。
English
Place value and powers of two
- In binary, each position is a power of two: 1, 2, 4, 8, 16, ...
- The byte
00010100is16 + 4 = 20. The rightmost bit is the 1s place. - An 8-bit byte can hold
0to255.
日本語
桁の位と2の累乗
- バイナリでは、各位置は2の累乗: 1, 2, 4, 8, 16, ... です。
- バイテ
00010100は16 + 4 = 20である。最も右側のビットは1の位である。 - 8ビットのバイテは
0から255までを保持できる。
English
Reading a bit with >> and & 1
- The shift
n >> imoves the bits right byiplaces, so bitilands in the 1s place. - The mask
& 1keeps only that lowest bit, giving0or1. - So
(n >> i) & 1reads the value of bit numberi.
日本語
>> と & 1 でビットを読み取る
- シフト
n >> iはビットを右にi個移動させ、bitiを1の位に置く。 - マスク
& 1は最低位のビットのみを残し、0または1を与える。 (n >> i) & 1は bit numberiの値を読み取ります。
English
The bitwise operators
&(and),|(or),^(xor),~(not) combine numbers bit by bit.<<and>>shift bits left or right. Shifting left by 1 doubles a number.- These are the tools for masks, flags, and low-level tricks.
日本語
ビット演算子
&(AND),|(OR),^(XOR),~(NOT) は、 numbers をビットごとに結合する。<<と>>はシフトによってビットを左または右に移動させる。1つ左にシフトすると、数値は倍になる。- これらはマスク、フラグ、低レベルのトリックに使うツールである。
#include <stdio.h>
int main(void) {
int n = 20;
for (int i = 7; i >= 0; i--) { // from the highest bit down
printf("%d", (n >> i) & 1);
}
printf("\n"); // 00010100
return 0;
}
English
Common mistakes
&is bitwise AND and&&is logical AND — do not confuse them.<< 1doubles a value;>> 1halves it.
日本語
よくあるミス
&はビットANDであり、&&は論理ANDである——混同しないように注意せよ。<< 1は値を倍にし、>> 1は半にする。
English
Now you try
- Use
(n >> i) & 1to read biti, and a loop to look at every bit. - For
count_bitsandget_bit, the parameter isunsigned int. Do not write amainfor those.
日本語
あなたも試してみよう
(n >> i) & 1を使用して bitiを読み取り、ループですべてのビットを確認します。count_bitsとget_bitに対して、パラメータはunsigned intである。それらに対してmainを書かないでください。
Explore · 探索
Bitwise operators
& | ^ ~ << >> work on each bit of a byte independently.
Complete int count_bits(unsigned int n) so it returns how many bits of n are 1. Use & 1 and >> in a loop. Do not write a main.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Complete int get_bit(unsigned int n, int i) so it returns bit number i of n (0 or 1). Use (n >> i) & 1. Do not write a main.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
The byte n is given. In main, print its 8-bit binary form (most significant bit first), then a newline. For 20 that is 00010100.
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。