Bits, binary, and bitwise operators · Bits, binario y operadores bit a bit
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.
Los números son bits
- Dentro del ordenador, cada
intes una fila de bits — cada bit es un0o un1. - Usualmente leemos los números en base 10, pero la máquina los almacena en base 2 (binario).
- Los operadores a nivel de bits permiten inspeccionar y modificar bits individuales.
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.
Valor posicional y potencias de dos
- En binario, cada posición representa una potencia de dos: 1, 2, 4, 8, 16, ...
- El byte
00010100equivale a16 + 4 = 20. El bit más a la derecha ocupa la posición de las unidades. - Un byte de 8 bits puede almacenar valores desde
0hasta255.
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.
Leer un bit con >> y & 1
- El desplazamiento
n >> imueve los bits hacia la derechaiposiciones, de modo que el bitiqueda en la posición de las unidades. - La máscara
& 1conserva únicamente ese bit menos significativo, devolviendo0o1. - Por tanto,
(n >> i) & 1lee el valor del 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.
Los operadores a nivel de bits
&(AND),|(OR),^(XOR),~(NOT) combinan números bit a bit.<<y>>desplazan bits a la izquierda o a la derecha. Desplazar a la izquierda por 1 duplica un número.- Estas son las herramientas para máscaras, banderas y trucos de bajo nivel.
#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.
Errores comunes
&es AND a nivel de bits y&&es AND lógico — no los confundas.<< 1duplica un valor;>> 1lo divide a la mitad.
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.
Ahora practica
- Usa
(n >> i) & 1para leer el biti, y un bucle para examinar todos los bits. - Para
count_bitsyget_bit, el parámetro esunsigned int. No escribas una funciónmainpara ellas.
Bitwise operators · Operadores bit a bit
& | ^ ~ << >> work on each bit of a byte independently. · & | ^ ~ << >> operan sobre cada bit de un byte de forma independiente.
Complete int count_bits(unsigned int n) so it returns how many bits of n are 1. Use & 1 and · y >> in a loop. Do not · no write a main. · Complete int count_bits(unsigned int n) para que devuelva cuántos bits de n son 1. Use & 1 y >> en un bucle. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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 · no write a main. · Complete int get_bit(unsigned int n, int i) para que devuelva el bit número i de n (0 o 1). Use (n >> i) & 1. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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. · Se da el byte n. En main, imprima su forma binaria de 8 bits (bit más significativo primero), seguido de un salto de línea. Para 20 esto es 00010100.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.