Changing bits in C programming

I program programming in C. Let's say I have a character: char letter = 0x0000; So the binary data for the letter is now “00000000”, let's say I want to change the binary data to “10000000” and then change to “10010000”, is there a bitwise operator or method that would allow me to change “0” to “1” or “1” to “0” in a specific position. Is it also possible?

+7
c bit-manipulation bitwise-operators
source share
3 answers

If you have XOR any bit with 1 bit, it toggles its value:

0 ^ 1 = 1 1 ^ 1 = 0 

Similarly, if you have XOR any bit with 0, it stores the same value:

 0 ^ 0 = 0 1 ^ 0 = 1 

Therefore, you can flip the nth bit of a number by XORing it with a number that has zero bits everywhere except for bit n:

 val ^= (1 << n); 

Hope this helps!

+8
source share

Yes, it is very possible. Just use a bitwise exclusive OR, or just an XOR operator for a number with a power of 2 n, where n is the digit you want to change. ^ is the XOR operator in C.

  000000 (decimal 0) ^ 100000 (decimal 32 = 2 power 5 = 1 << 5) = 100000 1010 (decimal 10) XOR 0010 (decimal 2 = 2 power 1 = 1 << 1) = 1000 

You can calculate 2 by power n by simply shifting the bits by 1 by n bits. Thus, 2 to 4 power can be obtained by shifting the bits in 1 to 4 places.

inputNum ^ (1 <n) will give what you need if switching is all you need.

 Bitwise XOR "^" bit a bit ba ^ b (a XOR b) 0 0 0 0 1 1 1 0 1 1 1 0 

However, remember that executing XOR on a bit that already has 1 will convert it to zero. because 1 ^ 1 = 0;

If you just want to convert 0 to 1 and save 1 if it already exists. You may need to use the bitwise operator Or.

 Bitwise OR "|" bit a bit ba | b (a OR b) 0 0 0 0 1 1 1 0 1 1 1 1 

Below is an example

  11001110 | 10011000 = 11011110 

Source: http://en.wikipedia.org/wiki/Bitwise_operations_in_C and http://en.wikipedia.org/wiki/Bitwise_operation

+3
source share

You can use the bitwise operator AND (&) and OR (|). For example:

01001000 | 10111000 = 11111000

This is done as follows: 72 | 184 = 248

(72 = 64 + 8)

See the following lesson for more details: http://www.cprogramming.com/tutorial/bitwise_operators.html

+1
source share

All Articles