Buscar, establecer, borrar, alternar y modificar bits en C

Dado un entero positivo N , la tarea es realizar la siguiente secuencia de operaciones en la representación binaria de N en C.

Ejemplos:

Entrada: N = 5, K = 1, P = 0
Salida:
K(= 1) th bit de 5 es 1.
Establecer el K(= 1) th bit modifica N a 5
Borrar K(= 1) th bit modifica N a 4.
Cambiar el K(= 1) th bit modifica N a 4.
Reemplazar el K(= 1) th bit con P(= 0) modifica N a 4

Entrada : N = 10, K = 2, P = 1
Salida: El bit
K (= 2) de 5 es 1. Al establecer el bit K (= 2) se modifica N a 10. Al borrar el bit K (= 2) modifica N a 8. Alternar el K(= 2) th bit modifica N a 8. Reemplazar el K(= 2) th bit con P(= 1) modifica N a 10.



Enfoque: siga los pasos a continuación para encontrar, establecer, borrar, alternar y modificar el K -ésimo bit en la representación binaria de N.

Encontrando un poco:

 (N >> K) & 1

Poniendo un poco:

 N = N | (1 << K)

Aclarando un poco:

 N = N & ~(1 << K)

Cambia un poco:

 N = N ^ (1 << K)

Modifica un poco:

 N = N | (P << K)

A continuación se muestra la implementación del enfoque anterior:

C

// C program to implement
// the above approach
  
#include <stdio.h>
  
// Function to set the kth bit of n
int setBit(int n, int k)
{
    return (n | (1 << (k - 1)));
}
  
// Function to clear the kth bit of n
int clearBit(int n, int k)
{
    return (n & (~(1 << (k - 1))));
}
  
// Function to toggle the kth bit of n
int toggleBit(int n, int k)
{
    return (n ^ (1 << (k - 1)));
}
  
// Function to modify k-th bit with p
int modifyBit(int n, int k, int p)
{
    return (n | (p << k));
}
  
// Function to find the kth bit of n
int findBit(int n, int k)
{
    return ((n >> k) & 1);
}
  
// Utility function to perform
// the specified Bit Operations
void bitOperations(int n, int k,
                   int p)
{
  
    printf("K(= %d)-th bit of %d is %d\n",
           k, n, findBit(n, k));
  
    printf("Setting K(= %d)th bit modifies N to %d\n",
           k, setBit(n, k));
  
    printf("Clearing K(= %d)th bit modifies N to %d\n",
           k, clearBit(n, k));
  
    printf("Toggling K(= %d)th bit modifies N to %d\n",
           k, toggleBit(n, k));
  
    printf("Replacing the K(= %d)<sup>th</sup> bit", k);
    printf(" with P(= %d) modifies N to 10\n",
           modifyBit(n, k, p));
}
  
// Driver Code
int main()
{
    int n = 5, k = 1, p = 1;
    bitOperations(n, k, p);
  
    return 0;
}
Producción:

K(= 1)-th bit of 5 is 0
Setting K(= 1)th bit modifies N to 5
Clearing K(= 1)th bit modifies N to 4
Toggling K(= 1)th bit modifies N to 4
Replacing the K(= 1)th bit with P(= 7) modifies N to 10

Complejidad de tiempo: O(log(N))
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por shahbazalam75508 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *