Bits, binary, and bitwise operators · Bits, binário e operadores bitwise
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.
Números são bits
- Dentro do computador, cada
inté uma fileira de bits — cada bit é um0ou um1. - Nós geralmente lemos números em base 10, mas a máquina os armazena em base 2 (binário).
- Operadores bitwise permitem olhar e alterar bits individuais.
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.
Posição decimal e potências de dois
- No binário, cada posição é uma potência de dois: 1, 2, 4, 8, 16, ...
- O byte
00010100é16 + 4 = 20. O bit mais à direita é a casa dos 1s. - Um byte de 8 bits pode armazenar valores de
0a255.
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.
Lendo um bit com >> e & 1
- O shift
n >> imove os bits para a direita emiposições, assim o biticai na casa dos 1s. - A máscara
& 1mantém apenas aquele bit mais baixo, resultando em0ou1. - Então
(n >> i) & 1lê o valor do bit númeroi.
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.
Os operadores bitwise
&(and),|(or),^(xor),~(not) combinam números bit a bit.<<e>>shift bits para a esquerda ou direita. Shift para a esquerda por 1 dobra um número.- Estas são as ferramentas para máscaras, flags e truques de nível baixo.
#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;
}
Common mistakes
&is bitwise AND and&&is logical AND — do not confuse them.<< 1doubles a value;>> 1halves it.
Erros comuns
&é AND bitwise e&&é AND lógico — não os confunda.<< 1dobra um valor;>> 1o divide pela metade.
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.
Agora você tenta
- Use
(n >> i) & 1para ler o biti, e um loop para olhar todos os bits. - Para
count_bitseget_bit, o parâmetro éunsigned int. Não escreva ummainpara esses.
Bitwise operators · Operadores bitwise
& | ^ ~ << >> work on each bit of a byte independently. · & | ^ ~ << >> trabalhe em cada bit de um byte independentemente.
Complete int count_bits(unsigned int n) so it returns how many bits of n are 1. Use & 1 and · e >> in a loop. Do not · não write a main. · Complete int count_bits(unsigned int n) para que retorne quantos bits de n são 1. Use & 1 e >> em um loop. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete int get_bit(unsigned int n, int i) so it returns bit number i of n (0 or · ou 1). Use (n >> i) & 1. Do not · não write a main. · Complete int get_bit(unsigned int n, int i) para que retorne o bit número i de n (0 ou 1). Use (n >> i) & 1. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · O byte n é fornecido. Em main, imprima sua forma binária de 8 bits (bit mais significativo primeiro), seguido de uma nova linha. Para 20 que é 00010100.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.