Operadores bit a bit de C ++

En este tutorial, aprenderemos sobre los operadores bit a bit en C ++ con la ayuda de ejemplos.

En C ++, los operadores bit a bit realizan operaciones con datos enteros a nivel de bit individual. Estas operaciones incluyen probar, configurar o cambiar los bits reales. Por ejemplo,

 a & b; a | b;

Aquí hay una lista de 6 operadores bit a bit incluidos en C ++.

Operador Descripción
& Operador AND bit a bit
| Operador OR bit a bit
^ Operador XOR bit a bit
~ Operador de complemento bit a bit
<< Operador de desplazamiento a la izquierda bit a bit
>> Operador de desplazamiento a la derecha bit a bit

Estos operadores son necesarios porque la Unidad Aritmético-Lógica (ALU) presente en la CPU de la computadora realiza operaciones aritméticas a nivel de bit.

Nota: Los operadores bit a bit solo se pueden usar junto con los tipos de datos chary int.

1. Operador AND bit a bit de C ++

El operador AND bit a bit & devuelve 1 si y solo si ambos operandos son 1 . De lo contrario, devuelve 0 .

La siguiente tabla muestra el funcionamiento del operador AND bit a bit . Vamos a y b ser dos operandos que sólo puede tomar valores binarios, es decir, 1 y 0 .

un segundo a & b
0 0 0
0 1 0
1 0 0
1 1 1

Nota: La tabla anterior se conoce como la "Tabla de verdad" para el operador AND bit a bit .

Echemos un vistazo a la operación AND bit a bit de dos enteros 12 y 25:

 12 = 00001100 (en binario) 25 = 00011001 (en binario) // Operación Y bit a bit de 12 y 25 00001100 y 00011001 _________ 00001000 = 8 (en decimal)

Ejemplo 1: AND bit a bit

 #include using namespace std; int main() ( // declare variables int a = 12, b = 25; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "a & b = " << (a & b) << endl; return 0; )

Salida

 a = 12 b = 25 a y b = 8

En el ejemplo anterior, hemos declarado dos variables ay b. Aquí, observe la línea,

 cout << "a & b = " << (a & b) << endl;

Aquí, estamos realizando AND bit a bit entre las variables ay b.

2. Operador OR bit a bit de C ++

El operador OR bit a bit | devuelve 1 si al menos uno de los operandos es 1 . De lo contrario, devuelve 0 .

La siguiente tabla de verdad demuestra el funcionamiento del operador OR bit a bit . Vamos a y b ser dos operandos que sólo puede tomar valores binarios, es decir, 1 o 0 .

un segundo a | segundo
0 0 0
0 1 1
1 0 1
1 1 1

Veamos la operación OR bit a bit de dos enteros 12 y 25 :

12 = 00001100 (en binario) 25 = 00011001 (en binario) O bit a bit Operación de 12 y 25 00001100 | 00011001 _________ 00011101 = 29 (en decimal)

Ejemplo 2: OR bit a bit

 #include int main() ( int a = 12, b = 25; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "a | b = " << (a | b) << endl; return 0; )

Salida

a = 12 b = 25 a | b = 29

El OR bit a bit de a = 12y b = 25da 29.

3. Operador XOR bit a bit de C ++

El operador XOR bit a bit ^ devuelve 1 si y solo si uno de los operandos es 1 . Sin embargo, si ambos operandos son 0 , o si ambos son 1 , el resultado es 0 .

La siguiente tabla de verdad demuestra el funcionamiento del operador XOR bit a bit . Vamos a y b ser dos operandos que sólo puede tomar valores binarios, es decir, 1 o 0 .

un segundo a b
0 0 0
0 1 1
1 0 1
1 1 0

Veamos la operación XOR bit a bit de dos enteros 12 y 25:

 12 = 00001100 (en binario) 25 = 00011001 (en binario) Operación XOR bit a bit de 12 y 25 00001100 00011001 _________ 00010101 = 21 (en decimal)

Ejemplo 3: XOR bit a bit

 #include int main() ( int a = 12, b = 25; cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "a b = " << (a b) << endl; return 0; )

Salida

 a = 12 b = 25 a b = 21

El XOR bit a bit de a = 12y b = 25da 21.

4. Operador de complemento bit a bit de C ++

El operador de complemento bit a bit es un operador unario (funciona solo en un operando). Se denota por ~que cambia los dígitos binarios 1 a 0 y 0 a 1 .

Complemento bit a bit

Es importante notar que el complemento bit a bit de cualquier entero N es igual a - (N + 1) . Por ejemplo,

Considere un número entero 35 . Según la regla, el complemento bit a bit de 35 debe ser - (35 + 1) = -36 . Ahora, veamos si obtenemos la respuesta correcta o no.

 35 = 00100011 (In Binary) // Using bitwise complement operator ~ 00100011 __________ 11011100

In the above example, we get that the bitwise complement of 00100011 (35) is 11011100. Here, if we convert the result into decimal we get 220.

However, it is important to note that we cannot directly convert the result into decimal and get the desired output. This is because the binary result 11011100 is also equivalent to -36.

To understand this we first need to calculate the binary output of -36. We use 2's complement to calculate the binary of negative integers.

2's Complement

The 2's complement of a number N gives -N.

In binary arithmetic, 1's complement changes 0 to 1 and 1 to 0.

And, if we add 1 to the result of the 1's complement, we get the 2's complement of the original number.

For example,

 36 = 00100100 (In Binary) 1's Complement = 11011011 2's Complement : 11011011 + 1 _________ 11011100 

Here, we can see the 2's complement of 36 (i.e. -36) is 11011100. This value is equivalent to the bitwise complement of 35 that we have calculated in the previous section.

Hence, we can say that the bitwise complement of 35 = -36.

Example 4: Bitwise Complement

 #include int main() ( int num1 = 35; int num2 = -150; cout << "~(" << num1 << ") = " << (~num1) << endl; cout << "~(" << num2 << ") = " << (~num2) << endl; return 0; )

Output

 ~(35) = -36 ~(-150) = 149

In the above example, we declared two integer variables num1 and num2, and initialized them with the values of 35 and -150 respectively.

We then computed their bitwise complement with the codes (~num1) and (~num2) respectively and displayed them on the screen.

 The bitwise complement of 35 = - (35 + 1) = -36 i.e. ~35 = -36 The bitwise complement of -150 = - (-150 + 1) = - (-149) = 149 i.e. ~(-150) = 149

This is exactly what we got in the output.

C++ Shift Operators

There are two shift operators in C++ programming:

  • Right shift operator >>
  • Left shift operator <<

5. C++ Right Shift Operator

The right shift operator shifts all bits towards the right by a certain number of specified bits. It is denoted by >>.

Cuando desplazamos cualquier número hacia la derecha, los bits menos significativos se descartan, mientras que los bits más significativos se reemplazan por ceros.

un poco Shift a la derecha

Como podemos ver en la imagen de arriba, tenemos un número de 4 bits . Cuando realizamos una un bit operación de desplazamiento a la derecha en ella, cada bit individual se desplaza a la derecha en 1 bit.

Como resultado, el bit más a la derecha se descarta, mientras que el bit más a la izquierda permanece vacío. Esta vacante se reemplaza por un 0 .

6. Operador de desplazamiento a la izquierda de C ++

El operador de desplazamiento a la izquierda desplaza todos los bits hacia la izquierda en un cierto número de bits especificados . Se denota por <<.

Desplazamiento a la izquierda un poco

As we can see from the image above, we have a 4-bit number. When we perform a 1 bit left shift operation on it, each individual bit is shifted to the left by 1 bit.

As a result, the left-most bit is discarded, while the right-most bit remains vacant. This vacancy is replaced by a 0.

Example 5: Shift Operators

 #include int main() ( // declaring two integer variables int num = 212, i; // Shift Right Operation cout << "Shift Right:" << endl; // Using for loop for shifting num right from 0 bit to 3 bits for (i = 0; i < 4; i++) ( cout <> " << i << " = " <> i) << endl; ) // Shift Left Operation cout << "Shift Left:" << endl; // Using for loop for shifting num left from 0 bit to 3 bits for (i = 0; i < 4; i++) ( cout << "212 << " << i << " = " << (212 << i) << endl; ) return 0; )

Output

 Shift Right: 212>> 0 = 212 212>> 1 = 106 212>> 2 = 53 212>> 3 = 26 Shift Left: 212 << 0 = 212 212 << 1 = 424 212 << 2 = 848 212 << 3 = 1696

From the output of the program above, we can infer that, for any number N, the results of the shift right operator are:

 N>> 0 = N N>> 1 = (N>> 0) / 2 N>> 2 = (N>> 1) / 2 N>> 3 = (N>> 2) / 2

and so on.

Similarly, the results of the shift left operator are:

 N << 0 = N N << 1 = (N << 0) * 2 N << 2 = (N << 1) * 2 N << 3 = (N << 2) * 2

and so on.

Hence we can conclude that,

 N>> m = ( N>> (m-1) ) / 2 N << m = ( N << (m-1) ) * 2

In the above example, note that the int data type stores numbers in 32-bits i.e. an int value is represented by 32 binary digits.

However, our explanation for the bitwise shift operators used numbers represented in 4-bits.

For example, the base-10 number 13 can be represented in 4-bit and 32-bit as:

 4-bit Representation of 13 = 1101 32-bit Representation of 13 = 00000000 00000000 00000000 00001101 

Como resultado, la operación de desplazamiento a la izquierda bit a bit para 13 (y cualquier otro número) puede ser diferente dependiendo del número de bits por los que están representados.

Porque en la representación de 32 bits , hay muchos más bits que se pueden desplazar hacia la izquierda en comparación con la representación de 4 bits .

Articulos interesantes...