How to replace 1 bit of an integer without changing the other neighboring bits?

2

I want to change 1 bit and keep the same values as other neighboring bits.

The bit operator shifts left or right by changing the 1-bit 0 bit, but it changes the entire 8-bit sequence. I did not want that to happen.

Alternatively, I change the integer itself, so the bit I want changes.

Please, can anyone help?

Thank you!

    
asked by anonymous 18.06.2017 / 20:57

2 answers

2

If you use XOR with 1 you can change a bit:

0 ^ 1 = 1
1 ^ 1 = 0

for example to change a 0 to a 4 we changed the 3rd bit.

char a = 0x00;
int bit = 2;
a ^= (1 << bit)
    
18.06.2017 / 22:06
2

The C language even allows us to use struct and union to be able to directly determine the value of one or more bits with the = operator. This functionality is little used - and anyway, it requires you to define a Union by naming bits (or fields with different sizes of bits).

To change a "generic" bit by one byte, the most common is:

  • create a number with the bit in the right position
  • Use the "|" operation ("or" binary) to set the bit

This is if you want to pass the bit always from 0 to 1. The use of "xor" will always reverse the bit. And if you want to delete a bit, then the process involves creating a mask where the desired bit has the value "0", and apply the "&" operation.

We can do a function to set or reset a bit that does this: receive a pointer for the byte to be changed, the bit position, and the desired value. We create the byte with the bit in "1" in the correct position - (using the << operator), from it we create a mask with that bit at zero, and apply the bit with the value sent. In C:

void altera_bit(char *alvo, char posicao, char valor) {
    char mascara = ~(1 << posicao);
    *alvo = (*alvo & mascara) | (valor << posicao);
} 
    
19.06.2017 / 14:18