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

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

The bit operator shifts left or right, changing the 1-pair 0 bit, but it changes the entire 8-bit sequence. I didn't want that to happen.

As an alternative, I change the integer itself, with this the bit I want is changed.

Please, can anyone help?

Thank you!

Author: LUIZ, 2017-06-18

2 answers

If we use XOR with 1 gives to exchange a bit:

0 ^ 1 = 1
1 ^ 1 = 0

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

char a = 0x00;
int bit = 2;
a ^= (1 << bit)
 2
Author: tomasantunes, 2017-06-18 20:06:37

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

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

  • Create a number with the bit in the right position
  • use the "|" ("or" binary) operation to set O bit

This if you want to pass the bit always from 0 to 1. Using the " 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 applying the operation"&".

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

void altera_bit(char *alvo, char posicao, char valor) {
    char mascara = ~(1 << posicao);
    *alvo = (*alvo & mascara) | (valor << posicao);
} 
 2
Author: jsbueno, 2017-06-19 12:41:05