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

Asked

Viewed 1,130 times

2

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

The bit operator shifts to the left or right by changing the bit of 1 pair 0, but it changes the entire 8-bit sequence. I didn’t mean for this to happen.

Alternatively, I change the integer itself, thereby changing the bit I wish to.

Please, can someone help?

Thank you!

2 answers

3

The C language even allows us to use structand union to be able to direct the value of one or more bits with the operator =. This functionality is rarely used - and anyway, requires you to define a Union by naming 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 at the right position
  • Use operation "|" ("or" binary) to set the bit

This is if you want to always pass the bit from 0 to 1. Using the "xor" will always invert the bit. And if you want to delete a bit, then the process involves creating a mask in which 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: get a pointer to the byte to change, the bit position, and the desired value. We create the byte with the bit in "1" at the correct position - (using the operator <<), from it we create a mask with this 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);
} 
  • Thank you all!

2


if we use XOR with 1 we can change 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)
  • Tomás, does it change the following? X = 150; /in binary = 10010110. Does your suggestion change the last bit from "0" to "1"? Resulting in the binary sequence 10010111, which changes the integer of variable X to 151?

  • then it would be simpler to do x += 1;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.